android: LayoutParams for TextView makes the view disappear, programmatically - android

I've hit this from various different angles. Basically the gist is this:
I've layed out a template in XML for an interface which NEEDS to be run programmatically, so it's going to be populated dynamically during the run.
The problem here, is that the XML TextView has quite a few layout tweaks (which work) and are necessary. But if I actually set them in code, the TextView doesn't even show up.
(The TextView, by the way, is nested inside a TableRow, thus the call to weight.)
The XML template I designed first, to use as reference for the code is this, and it works just fine:
<TextView
android:id="#+id/txtviewWhiteBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:background="#drawable/textview_9patch_white"
android:gravity="center"
android:text="75"
android:textColor="#android:color/black"
android:layout_margin="20dp"
android:padding="20dp"
android:textSize="40dp" />
Like I said, that lays out perfectly.
When I run the same layout in code though, and apply LayoutParams, the TextView disappears.
Here's the relevant snippet:
int textViewExampleID = 9001;
private TextView txtviewExample = new TextView(this);
private void buildTextView(){
LayoutParams paramsExample = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,1.0f);
txtviewExample.setId(textViewExampleID);
txtviewExample.setBackgroundResource(R.drawable.textview_9patch_white);
txtviewExample.setGravity(Gravity.CENTER);
txtviewExample.setTextColor(getResources().getColor(android.R.color.black));
paramsExample.setMargins(20, 20, 20, 20);
txtviewExample.setPadding(20, 20, 20, 20);
txtviewExample.setTextSize(40);
txtviewExample.setText("customExample");
//if I comment out the following line, this TextView displays.
//if I leave it in, it doesn't display.
txtviewExample.setLayoutParams(paramsExample);
}
I realize there's all sorts of available classes for LayoutParams, and I've been playing with them all
LinearLayout.LayoutParams, TableView.LayoutParams, RelativeLayout.LayoutParams, LayoutParams just by itself...
No matter which one I try, any attempt at calling "setLayoutParams" renders the entire TextView gone.
I've scoured the forums here, and haven't quite found the answer. This can't be THAT uncommon.

well, that was painful but I finally got it figured out.
The most important thing to remember (that I just realized) is that of all the myriads of LayoutParams, you need to use the one that relates to the PARENT of the view you're working on, not the actual view.
So in my case, I was trying to get the TextView margins working, but it was being put inside a TableRow. The one simple change was ensuring that the type of LayoutParams being used were the ones for TableRow:
private void buildTextView(){
// the following change is what fixed it
TableRow.LayoutParams paramsExample = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,1.0f);
txtviewExample.setId(textViewExampleID);
txtviewExample.setBackgroundResource(R.drawable.textview_9patch_white);
txtviewExample.setGravity(Gravity.CENTER);
txtviewExample.setTextColor(getResources().getColor(android.R.color.black));
paramsExample.setMargins(20, 20, 20, 20);
txtviewExample.setPadding(20, 20, 20, 20);
txtviewExample.setTextSize(40);
txtviewExample.setText("customExample");
txtviewExample.setLayoutParams(paramsExample);
}
Thanks guys, hopefully this will come in handy for somebody else down the line, as I saw a lot of semi-related questions in the forums here, but not one that really defines the problem.

private TextView txtviewExample = new TextView(this);
private void buildTextView(){
LayoutParams paramsExample = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,1.0f);
txtviewExample.setId(textViewExampleID);
txtviewExample.setBackgroundResource(R.drawable.textview_9patch_white);
txtviewExample.setGravity(Gravity.CENTER);
txtviewExample.setTextColor(getResources().getColor(android.R.color.black));
paramsExample.setMargins(20, 20, 20, 20);
txtviewExample.setPadding(20, 20, 20, 20);
txtviewExample.setTextSize(40);
txtviewExample.setText("customExample");
setContentView(txtviewExample);//when you don't use SETTER method for TextView you can't view the desireable text on the UI//
}
//use

what is the 3rd variable in layoutparams supposed to do, is that alpha? what happens if you comment out paramsExample.setMargins
finally what happens if you to txtviewExample.setVisible(View.Visible) after you setLayoutParams?
those would be the things I would try if you haven't

Related

How do I layout my React Native Fire TV SubtitleView correctly?

I am working on a React Native implementation of the Bitmovin player using their Android SDK. At this stage, I'm not sure how specific this is to the Bitmovin player, but as they don't officially support React Native at this stage, I want to ask about this on SO first. This is a React Native UI Component with a custom view, using a layout file. I am trying to present a subtitle view on top of a player view, and I have based my layout on Bitmovin's simple examples. In fact I have simplified the layout even further:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<com.bitmovin.player.PlayerView
android:id="#+id/bitmovinPlayerView"
app:shutter_background_color="#android:color/transparent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bootsplash_background">
<com.bitmovin.player.SubtitleView
android:id="#+id/bitmovinSubtitleView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:foregroundGravity="center" />
</com.bitmovin.player.PlayerView>
</LinearLayout>
This presents the SubtitleView at the top of the screen. Nothing I have tried so far presents the SubtitleView at the bottom of the screen in the more common position. I have experimented with every single parameter on all of these elements, as far as I can tell. Here is the code that initialises the view:
public void init() {
inflate(context, R.layout.player_container, this);
StyleConfig styleConfig = new StyleConfig();
styleConfig.setUiEnabled(false);
PlayerConfig playerConfig = new PlayerConfig();
playerConfig.setStyleConfig(styleConfig);
playerView = findViewById(R.id.bitmovinPlayerView);
player = Player.create(context, playerConfig);
playerView.setPlayer(player);
player.on(SourceEvent.Loaded.class, this::onLoad);
player.on(PlayerEvent.Playing.class, this::onPlay);
player.on(PlayerEvent.Paused.class, this::onPause);
player.on(PlayerEvent.Seek.class, this::onSeek);
player.on(PlayerEvent.TimeChanged.class, this::onTimeChanged);
player.on(PlayerEvent.Destroy.class, this::onDestroy);
player.on(PlayerEvent.Seeked.class, this::onSeeked);
player.on(PlayerEvent.PlaybackFinished.class, this::onPlaybackFinished);
player.on(PlayerEvent.Ready.class, this::onReady);
player.on(SourceEvent.Error.class, this::onError);
player.on(SourceEvent.SubtitleChanged.class, this::onSubtitleChanged);
player.on(PlayerEvent.Error.class, this::onError);
subtitleView = findViewById(R.id.bitmovinSubtitleView);
subtitleView.setPlayer(player);
player.setVolume(100);
}
I have read that React Native styles the top-level view of a UI Component, so this is my only clue at this stage. I'm unsure how to respond to that info however...
EDIT: The problem is likely to be that dynamically updating view layouts in Android in React Native is not straightforward. This has been discussed at length here.
EDIT 2: I have tried to listen for global layout changes, which is one of the proposed workarounds for view layout issues:
getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
requestLayout();
}
});
This is called as expected, but has no effect on the subtitleView, which still displays at the top of the player, which seems to be because it has a height of 0.
EDIT 3: Another suggested solution that didn't work for me:
private void setupLayoutHack() {
Choreographer.getInstance().postFrameCallback(new Choreographer.FrameCallback() {
#Override
public void doFrame(long frameTimeNanos) {
manuallyLayoutChildren();
getViewTreeObserver().dispatchOnGlobalLayout();
Choreographer.getInstance().postFrameCallback(this);
}
});
}
private void manuallyLayoutChildren() {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
child.layout(0, 0, child.getMeasuredWidth(), child.getMeasuredHeight());
}
}
I called setupLayoutHack() in the constructor but saw no difference after applying those changes either :(
EDIT 4: My final attempt at fixing the SubtitleView layout was experimenting with measuring and laying out in various ways:
private void refreshViewChildrenLayout(View view){
view.measure(
View.MeasureSpec.makeMeasureSpec(view.getMeasuredWidth(), View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(view.getMeasuredHeight(), View.MeasureSpec.EXACTLY));
view.layout(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
}
However, the height in all cases that I tried was 0, which meant nothing was altered. There is a solution mentioned in the above RN issue that suggests that the shadow node for the subtitle view should be overridden. So one way forward could be to build a new subtitle view that has that included.
However, at this stage it seems to me an easier approach to respond to subtitle cues in React Native and perform all display and styling there.
(There is also a lesser issue of how to make the background on either side of the text transparent, but the layout issue is far more important at this stage).
Disclaimer: I'm not very familiar with React Native and how it influences layout creation if at all.
However looking at your layout file, it indicates that the SubtitleView is the top child of the PlayerView, which is a FrameLayout, thus gets added at the top (left). By specifying android:layout_height="wrap_content" on the SubtitleView it will only take up space that is required by the view. In the Bitmovin sample, it is generated in code and therefore should inherit the attributes from the parent, which is a RelativeLayout with android:layout_weight="1" which results in stretching it's height to the space available.
Long story short, try setting the height of your SubtitleView to match_parent

Android Studio How To Set Constraints And Use LayoutParams Dynamically

In my Android Application I want to create a bunch of ConstraintLayouts where each has for example an ImageView and a TextView in them.
Everything is created from code exept for one TableRow with which I will start out. My Problem ist that despite being able to set the margins via LayoutParams for the ConstraintLayout, the ImageView and the TextView do not change at all when I try to set the margins.
public fun generateAsset(tableRow: TableRow) {
// <android.support.constraint.ConstraintLayout
// android:layout_margin="4dp"
// android:background="#drawable/x32_tile_dark">
val clayout = ConstraintLayout(context)
tableRow.addView(clayout)
val cparams = clayout.layoutParams as TableRow.LayoutParams
cparams.setMargins(4, 4, 4, 4) // <--- Works correctly!
clayout.layoutParams = cparams
clayout.setBackgroundResource(R.drawable.x32_tile_dark)
// <ImageView
// android:layout_width="0dp"
// android:layout_height="60dp"
// android:layout_marginTop="8dp"
// app:srcCompat="#drawable/x256_spaceship_door_gray_blue" />
val iView = ImageView(context)
clayout.addView(iView)
val iparams = iView.layoutParams as ConstraintLayout.LayoutParams
iparams.width = ConstraintLayout.LayoutParams.MATCH_PARENT
iparams.height = 200
iparams.setMargins(8, 8, 8, 8) // <--- Does not do anything!
iView.layoutParams = iparams
iView.setImageResource(R.drawable.x256_spaceship_door_gray_blue)
// <TextView
// android:text="Massive Spaceship Door"
// android:layout_marginLeft="8dp"
// android:layout_marginRight="8dp"
// android:layout_marginBottom="4dp"
// android:textColor="#android:color/white" />
val ntext = TextView(context)
clayout.addView(ntext)
val nparams = ntext.layoutParams as ConstraintLayout.LayoutParams
nparams.setMargins(8, 8, 8, 8) // <--- Does not do anything!
ntext.layoutParams = nparams
ntext.setTextColor(Color.WHITE)
ntext.text = assetName
}
The reason why this doesn't work is probably because I haven't set the constraints of the ImageView and the TextView but how do I do that in code?
The ImageView should be right in the center of the ConstraintLayout while the TextView is supposed to be in the center but at the bottom.
How can I set the constraints to do what I've described above?
You are right to suspect that not setting the constraints may be the issue. To set constraints programmatically take a look at ConstraintSet.
This class allows you to define programmatically a set of constraints to be used with ConstraintLayout. It lets you create and save constraints, and apply them to an existing ConstraintLayout.
As an added bonus, ConstraintSet permits the setting of margins while setting constraints.
There are some good tutorials online about how to use ConstraintSet.
Not 100% sure here, but i have a suggestion and believe you have to call
iView .updateMargins<ConstraintLayout.LayoutParama>{//do some stuff here}.
You probably ask "Why?".
Well, i think its because you already created val clayout = ConstraintLayout(context) but didnt specify which attributesSet it has, thus taking the default one. And since your View already has defaultParams, they need to be updated now.
But please do some independet reasearch or ask a real expert with real knowledge. Because i am not really sure and this is just some suggestion.

The layout rules align_parent_end property does not show as true

At a point in my app I'm cycling through the objects on screen and checking if they're the last object in that line. To do that, I'm checking the Align Parent End property (which is checked for the last widget in each line). Here's part of my activity xml:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/relativeLayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Average Temperature:"
android:id="#+id/AverageTemperatureText"
android:layout_below="#+id/TemperaturesText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/AvgTempNum"
android:layout_alignBottom="#+id/AverageTemperatureText"
android:layout_toRightOf="#+id/AverageTemperatureText"
android:layout_below="#+id/TempMiddle"
android:gravity="center|bottom"
android:editable="false"
android:text="0.0"
android:maxLength="7"
android:nextFocusForward="#+id/TotalObservedVolumer"
android:layout_alignRight="#+id/FreeWaterVolume"
android:layout_alignEnd="#+id/FreeWaterVolume"
android:layout_alignParentEnd="true" />
^^^^ Right here. It's true.
You get the idea. Then, in my code, I'm cycling through the relative layout children, then for each view on it, checking it for that particular property. If it's true, I'm supposed to do something. But with the code I have, it's always false. So what am I doing wrong? Here it is:
RelativeLayout relLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
for(int i = 0; i < relLayout.getChildCount(); i++) {
View view = relLayout.getChildAt(i);
// Assess if it's the last field in that line
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view.getLayoutParams();
int[] rules = params.getRules();
if (rules[RelativeLayout.ALIGN_PARENT_END] == RelativeLayout.TRUE) {
// my code
}
}
Thanks!!
Fixed, but in a curious way.
In my case, all the last fields on screen had Align Parent End flagged. So I found online this would be the way to do it:
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view.getLayoutParams();
int[] rules = params.getRules();
if ((rules[RelativeLayout.ALIGN_PARENT_END] == RelativeLayout.TRUE)) {
// Do something about it
}
Where RelativeLayout.ALIGN_PARENT_END stands for 21, according to http://developer.android.com/reference/android/widget/RelativeLayout.html
However, my code was returning false for that check. So I started displaying the value for the property, and it really was false. I tried this for a while, then I saw one of my edittexts returned true for it. But the activity xml showed this
android:layout_alignParentRight="true"
in addition to alignParentEnd. Which didn't make sense, since alignParentRight is supposed to be rule 11, according to the same link above.
So I devised this code to expose which rules where true, and put it in my code:
for(int x = 0; x < 22; x++) {
if (rules[x] == RelativeLayout.TRUE) Log.i("Property true:", String.valueOf(x));
}
Which gave me 11 for all fields, and 11 and 21 for the field that responded TRUE before. Remember, all fields had android:layout_alignParentEnd="true" in the activity xml.
So to fix my code, I'm now checking rules[RelativeLayout.ALIGN_PARENT_RIGHT] and it works, but I strongly believe those two properties are switched somehow. Can anybody confirm? Or please englighten me on where I screwed up, which is more likely :)

Android: requestLayout() improperly called

The following error occurs when I attempt to inflate a layout within a ListView:
requestLayout() improperly called by android.widget.TextView{...} during layout: running second layout pass
I am attempting to inflate a layout within a ListView as follows:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) musicActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item, parent, false);
...
}else{...}
}
The layout being inflated can look as simple as the following, and will still produce the error
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/txt_size"/>
I have looked into similar questions, and no solutions found seem to work Question 1, Question 2, Question 3.
Does anyone know what causes this type of error? Any troubleshooting advice? For more context, this ListView is displayed within a Fragment within a ViewPager
UPDATE
Here is the full XML Layout (minus a bunch of attributes), that still results in the problem
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/txt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/txt3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/txt4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
Based on this, I would think the XML itself is not a problem, unless it has to do with the fact that I am using a ViewPager and Fragments
This issue seems to be a bug in the android implementation, please see: https://code.google.com/p/android/issues/detail?id=75516
Activating the fast scroll feature of a ListView in your code via ListView.setFastScrollEnabled(true) will trigger this bug and you'll start seeing the
requestLayout() improperly called by android.widget.TextView{...}
during layout: running second layout pass
message in your console.
This bug must have been introduced in one of the KitKat (4.4.x) updates, as I've not seen it with the initial KitKat (4.4.0) release. Apart from the ugly console spamming with the debug message from above, there seem to be no other impacts (maybe performance in some cases, which I haven't tested).
Cheers
PS: it's not the first time that the fast scroll feature is bugged, e.g. https://code.google.com/p/android/issues/detail?id=63545, 63545 was fixed in KitKat 4.4.3 but 75516 poped up thereafter --> seems to be a vexed subject for google ;-)
EDIT May 12 2015:
I updated my Nexus 7 to Android 5.1 some minutes ago (was Running 5.0 before) and stopped seeing this issue in this new version. As the appearance of the FastScroll indicator also changed in 5.1, I assume that google fixed this issue or at least commented out those ugly lines that spammed the console...
75516 & 82461 are still 'unresolved', but I guess that those refer to the same issue, that's now resolved in 5.1.
The problem is that while the method getView() of your adapter is displaying your layout some other code is trying to access this view to display it, resulting in a collision.
Note that some methods, that maybe you don't take care of (like setScale(), setTypeFace()) indeed call requestLayout(), so it would be interesting what you are doing after your inflate statement.
For me this issue was occurring upon a setLayoutParams() call. The solution was posting a runnable on the looper:
// java
imageView.post(new Runnable() {
#Override public void run() {
imageView.setLayoutParams(params);
}
});
// kotlin
post(Runnable { imageView.setLayoutParams(params) })
I fixed this issue by disabling fastScroll on the ListView in the XML.
<ListView
android:id="#+id/mListview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:fastScrollEnabled="false"
/>
In my case (Samsung Galaxy S4, API 21) this happened in ListView with EditTexts. I have a listener for field validation. Something like:
edit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
error.setVisibility(View.INVISIBLE);
error.setText("");
} else {
String s = edit.getText().toString();
if (s.isEmpty()) {
error.setText("Error 1");
} else if (s.length() < 2 || s.length() > 100) {
error.setText("Error 2");
}
error.setVisibility(View.VISIBLE);
}
}
});
After settinging focus in one of these EditTexts an above check is called. After that a TextView will change (the TextView contains an error message and lies over the EditText).
Setting focus to the second or the third EditText led to permanent request of the first EditText and return to current. An applications runs in infinite loop of requests (focus edittext 1, unfocus edittext 1, focus 3, unfocus 3, focus 1, etc).
I tried to set listView.setFastScrollEnabled(false). Also I tried a requestLayout() of some elements like in https://github.com/sephiroth74/HorizontalVariableListView/issues/93 with no chances.
Currently I made that TextView of fixed width and height in XML:
<TextView
android:id="#+id/error"
android:layout_width="match_parent" (or "200dp", but not "wrap_content")
android:layout_height="20dp"
.../>
After some experiments I noticed that a height of 20dp can be replaced with "wrap_content". But if a text is too long that divides into 2 lines, the application again catches in the infinite loop. So, android:singleLine="true" will help. It is deprecated, but amazingly android:maxLines="1" with android:lines="1" don't help as they again request layout.
Eventually we have:
<TextView
android:id="#+id/error"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:textColor="#f00"
android:textSize="20sp"
tools:text="Error message"/>
That's not a good solution, but at least it breaks the infinite loop.
This might happen if you are using some 3rd party extension of ListView. Replace that with standard ListView and check if it still throws the error.
I had similar problem. Please check Android layout: running second layout pass and my answer.
I had the same issue with Kitkat 4.4.4 on Motorola X with Genymotion. In my case the list item is a simple CheckedTextView and the error occurred in AppCompatCheckedTextView.
As a normal implementation I inflated the item from XML layout file like below:
if (convertView == null) {
convertView = inflater.inflate(R.layout.checkable_list_entry, parent, false);
}
After some trying I found out that this has something to do with XML inflation. I don't know the root cause, but as a solution I decided to inflate the list item by code and set all the properties by code too.
It ended up like this:
CheckedTextView view;
if (convertView == null) {
view = new CheckedTextView(parent.getContext());
view.setMinHeight(getResources().getDimensionPixelSize(R.dimen.default_touch_height));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
view.setTextAppearance(R.style.SectionEntry);
} else {
view.setTextAppearance(parent.getContext(), R.style.SectionEntry);
}
view.setBackgroundResource(R.drawable.form_element);
view.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
view.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT));
} else {
view = (CheckedTextView) convertView;
}
I had a problem with the same warning log :
requestLayout() improperly called by android.support.v7.widget.AppCompatTextView {...} during layout: running second layout pass
I was working with recylcerview and going to update it with new data.
The only solution that worked for me is as below :
Step(1). Remove current data :
public void removeAll() {
items.clear(); //clear list
notifyDataSetChanged();
}
Step(2). When you want to populate the recyclerview with new data, first set a new LayoutManager to recyclerview again:
private void initRecycleView() {
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false));
}
Step(3). Update the recyclerview with new data. for example :
public void refreshData(List newItems) {
this.items = newItems;
notifyItemRangeChanged(0, items.size());
}
Try taking off the textSize from the xml and setting it in Java code. I think that's causing it to be laid out twice.
In my case this warning prevented a button from showing up in API 21 devices. The button visibility was previously set to GONE.
The only workaround I got it was setting to INVISIBLE instead of GONE for API 21. It wasn't a real solution but it was acceptable for me.
I only post this because it can be useful from somebody.
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
theButton.setVisibility(View.INVISIBLE);
}
else {
theButton.setVisibility(View.GONE);
}
Sometimes you maybe already fixed the issue but it still keeps same error, so you need to close visual studio then delete all bin and obj folders from your projects, then uninstall the app from the emulator. then walah!! everything will works fine
I solved the problem like this:
mHolder.txt_fword.setTextSize(22);
mHolder.txt_farth.setTextSize(22);
mHolder.txt_fdef.setTextSize(22);
mHolder.txt_fdef2.setTextSize(22);
mHolder.txt_frem.setTextSize(22);
//if (fdef2.get(pos).equals("")) mHolder.txt_fdef2.setVisibility(View.GONE);
//if (frem.get(pos).equals("")) mHolder.txt_frem.setVisibility(View.GONE);
issue is .setVisibility(View.GONE); , change to .setVisibility(View.VISIBLE);

Change value in layout.xml conditionally in Android

I'm trying to get android:layout_marginEnd="-6dp" to change to 2dp conditionally in:
<FrameLayout
android:id="#+id/wifi_combo"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginEnd="-6dp"
>
My condition is:
if (mSignalClusterStyle == STYLE_ALWAYS) {
mMobileType.setVisibility(View.VISIBLE);
} else if (mWifiVisible) {
mMobileType.setVisibility(View.GONE);
}
I would like to add a line to the if statement that overrides the -6dp with 2dp in the xml file.
I have explored setMarginEnd(), but there are very few resources on this, seeing as it is only a year old, and I keep getting a compile error with it.
What is the best way to change android:layout_marginEnd on a condition programmatically?
FrameLayout layout = (FrameLayout) findViewById(R.id.wifi_combo);
FrameLayout.LayoutParams params = (LayoutParams) layout.getLayoutParams();
params.setMarginEnd(2);
The correct way to set the endMargin is using setMarginEnd() only, added in API 17.
http://developer.android.com/reference/android/view/ViewGroup.MarginLayoutParams.html#setMarginEnd(int)
BTW, what compile errors you are getting?

Categories

Resources