Setting LayoutParams programmatically - android

I want to set my LinearLayout's parameters after all of the views' parameters are calculated.
I am trying to set LinearLayout's height related to the parent view's height. And parent view's height is calculated according to its layout_weight, so I get the height by getMeasuredHeight();
My code :
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
RelativeLayout lay = (RelativeLayout) findViewById(R.id.alt);
LinearLayout bar = (LinearLayout) findViewById(R.id.barLay);
int layH = lay.getMeasuredHeight();
int barH = layH / 4;
LinearLayout.LayoutParams params = (LayoutParams) bar.getLayoutParams();
params.height = barH;
bar.setLayoutParams(params);
}
Eclipse Debugger stops the program at this line;
LinearLayout.LayoutParams params = (LayoutParams) bar.getLayoutParams();
I can't find what could be the problem? Am I doing something wrong to set params?

The type of LayoutParams are actually set by the parent of the view, so bar.getLayoutParams() should be returning an object of type RelativeLayout.LayoutParams. With an explicit cast to LinearLayout.LayoutParams I'd expect your logcat to contain a line like this:
Caused by: java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
Changing it to this should do the trick:
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) bar.getLayoutParams();
or, since height is in the base class, don't cast it at all:
ViewGroup.LayoutParams params = bar.getLayoutParams();

Try changing this
LinearLayout.LayoutParams params = (LayoutParams) bar.getLayoutParams();
to this
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bar.getLayoutParams();

After #LocHa asked me the type of the layouts, I try changing the parent layout's type to LinearLayout which was RelativeLayout, and finally it worked for me.

Related

How to programmatically set a TextView width and height to Wrap Content

I am writing a table programmatically from an SQLite database.
In a loop I am generating needed TextViews and am attempting to wrap the data in a TextView called descCol when the data is longer than the existing screen allows.
Suggestions to do this were offered in the following link:
Setting width to wrap_content for TextView through code
However when using either of the suggested methods I'm getting a java.lang.NullPointerException.
Here's my code example:
TextView descCol = new TextView(this);
descCol.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
In this case debug shows it throws a java.lang.NullPointerException on the getLayoutParams() line.
Also I've tried:
TextView descCol = new TextView(this);
ViewGroup.LayoutParams params = descCol.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
params.width = ViewGroup.LayoutParams.WRAP_CONTENT;
descCol.setLayoutParams(params);
In this case debug shows it throws a java.lang.NullPointerException on the params.height line.
Debug shows that in either case after performing the getLayoutParams() method, params is equal to null, apparently throwing the exception.
I've tried to assign other parameters first to descCol (textcolor, text, gravity etc.) prior to the getLayoutParams() but get the same result.
Suggestions as to how to avoid the java.lang.NullPointerException would be appreciated.
Also I was able to accomplish my task programmatically by simply using the setWidth and setHeight methods.
textview.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
textview.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
Try this way:
LinearLayout.LayoutParams textParam = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
textView.setLayoutParams(textParam);
Why are you using getLayoutParams() when you didnt even set the layout Params ?
You need to setLayout Params first. like this.
TextView view = new TextView(this);
view.setText("example textview ");
//adding layout properties
view.setLayoutParams(new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0));
// add the textview to the parentLayout
parentLayout.addView(view);

How to set the percentage height/width of child views of PercentFrameLayout at runtime

I want to set the child view's height/width of PercentFrameLayout programmatically. How to set the percentage height/width of child views of PercentFrameLayout at runtime..
I assume that you have View with Id view_child inside of your PercentLayout.
so use this code snippet
View view = findViewById(R.id.view_child);
PercentRelativeLayout.LayoutParams params =(PercentRelativeLayout.LayoutParams) view.getLayoutParams();
// This will currently return null, if view not exist in your xml.
PercentLayoutHelper.PercentLayoutInfo info = params.getPercentLayoutInfo();
info.heightPercent = 0.60;
view.requestLayout();
hope this help..
ImageView child= new ImageView(getActivity());
percentRelativeLayout.addView(child);
PercentRelativeLayout.LayoutParams params = (PercentRelativeLayout.LayoutParams) child.getLayoutParams();
PercentLayoutHelper.PercentLayoutInfo info = params.getPercentLayoutInfo();
info.heightPercent = 0.05f;
info.widthPercent = 0.05f;
info.leftMarginPercent = 0.5f;
child.setLayoutParams(params);

Change LinearLayout height to 0 programmatically

I am resizign LinearLayout from it's original height to 0 with:
ViewGroup.LayoutParams params = getLayoutParams();
params.height = newHeight;
requestLayout();
Everything works except newHeight = 0 - layout's height changes back to its original height. How can I avoid it ?
Setting visibility to GONE if newHeight == 0 does not help.
Try this.....
LinearLayout layout = (LinearLayout)findViewById(R.id.yourLayoutId);
LinearLayout.LayoutParams lp = (LayoutParams) layout.getLayoutParams();
lp.height = 0;
layout = (LinearLayout)findViewById(R.id.linearTop);
layout.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
ViewGroup.LayoutParams params = layout.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
layout.setLayoutParams(params);
Wouldn't you have to set the height of params using setBaseAttributes()? The int height = ... will not have any influence on params...
Are you sure that you get the actual parameters object, not the copy of one?
I would try the following code:
ViewGroup.LayoutParams params = getLayoutParams();
params.height = newHeight;
setLayoutParams(params);
requestLayout();
Try setting a new layout params object then. This should work
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT,0);
layout.setLayoutParams(lp);

How to add margin to a Button at run time?

I have to add more than one buttons on a LinearLayout. But I want to put those buttons say 5px apart. I could not find a way to set a margin of a Button. Any idea?
Use the layout_margin property of the button element. Does that not work?
<Button android:layout_margin="5px" (...)/>
Edit
When creating a button in java, LayoutParams is used to specify margins and so.
Button button = new Button();
(....)
params = new LinearLayout.LayoutParams();
params.leftMargin = 5;
(set params as you need)
parent.addView(button, params);
The LayoutParams you use must match the Layout you add your button in (see http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html). For a LinearLayout, use a LinearLayout.LayoutParams and set the *Margin fields accordingly.
Try this:
//Assuming your button is in a LinearLayout as stated
LinearLayout.LayoutParams params = myButton.getLayoutParams();
params.setMargins(0, 0, 0, 0) //left, top, right, bottom
myButton.setLayoutParams(params);
MarginLayoutParams params = (MarginLayoutParams) vector8.getLayoutParams();
params.width = 200; params.leftMargin = 100; params.topMargin = 200;
vector8.setLayoutParams(params);
Need use type of: MarginLayoutParams
Adding padding to the buttons would also solve your problem. Check this out
http://developer.android.com/resources/tutorials/views/hello-formstuff.html#CustomButton
use this code to set margin at runtime
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) btnContainer.getLayoutParams();
params.setMargins(5, 50, 10, 0); //left, top, right, bottom
view_whwre_set_margin.setLayoutParams(params);

How to set layout_weight attribute dynamically from code?

How can I set the value for the attribute layout_weight for button in android dynamically from java code ?
You can pass it in as part of the LinearLayout.LayoutParams constructor:
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
1.0f
);
YOUR_VIEW.setLayoutParams(param);
The last parameter is the weight.
Use LinearLayout.LayoutParams:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
Button button = new Button(this);
button.setLayoutParams(params);
EDIT: Ah, Erich's answer is easier!
If you already define your view in your layout(xml) file, only want to change the weight programmatically, this way is better
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)
mButton.getLayoutParams();
params.weight = 1.0f;
mButton.setLayoutParams(params);
new a LayoutParams overwrites other params defined in you xml file like margins, or you need to specify all of them in LayoutParams.
If the constructor with width, height and weight is not working, try using the constructor with width and height. And then manually set the weight.
And if you want the width to be set according to the weight, set width as 0 in the constructor. Same applies for height.
Below code works for me.
LinearLayout.LayoutParams childParam1 = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT);
childParam1.weight = 0.3f;
child1.setLayoutParams(childParam1);
LinearLayout.LayoutParams childParam2 = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT);
childParam2.weight = 0.7f;
child2.setLayoutParams(childParam2);
parent.setWeightSum(1f);
parent.addView(child1);
parent.addView(child2);
If layoutparams is already defined (in XML or dynamically), Here's a one liner:
((LinearLayout.LayoutParams) mView.getLayoutParams()).weight = 1;
If I someone looking for answer, use this:
LinearLayout.LayoutParams lay = (LinearLayout.LayoutParams) myLayout.getLayoutParams();
lay.weight = 0.5;
If you are initializing your layout from xml file, this will be much more convenient than providing new layout parameters for Linear Layout.
Any of LinearLayout.LayoutParams and TableLayout.LayoutParams worked for me, for buttons the right one is TableRow.LayoutParams. That is:
TableRow.LayoutParams buttonParams = new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT, 1f);
About using MATCH_PARENT or WRAP_CONTENT be the same.
If you have already defined your view in layout(xml) file and only want to change the weight pro grammatically, then then creating new LayoutParams overwrites other params defined in you xml file.
So first you should use "getLayoutParams" and then setLayoutParams
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mButton.getLayoutParams();
params.weight = 4f;
mButton.setLayoutParams(params);
I have done my task by adding this line of code!
LinearLayout.LayoutParams mylayout = (LinearLayout.LayoutParams)
myview.getLayoutParams();
mylayout.weight = 2;
myview.setLayoutParams(mylayout);
Using Kotlin you can do something like:
import android.content.Context
import android.support.v4.content.ContextCompat
import android.support.v7.widget.CardView
import android.widget.*
import android.widget.LinearLayout
class RespondTo : CardView {
constructor(context: Context) : super(context) {
init(context)
}
private fun init(context: Context) {
val parent = LinearLayout(context)
parent.apply {
layoutParams = LinearLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT, 1.0f).apply {
orientation = LinearLayout.HORIZONTAL
addView(EditText(context).apply {
id = generateViewId()
layoutParams = LinearLayout.LayoutParams(0,
LinearLayout.LayoutParams.WRAP_CONTENT, 0.9f).apply {
}
})
addView(ImageButton(context).apply({
layoutParams = LinearLayout.LayoutParams(0,
LinearLayout.LayoutParams.WRAP_CONTENT, 0.1f)
background = null
setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_save_black_24px))
id = generateViewId()
layoutParams = RelativeLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT).apply {
addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
// addRule(RelativeLayout.LEFT_OF, myImageButton.id)
}
}))
}
}
this.addView(parent)
}
}
if you want to set weight to LinearLayout then use code mentioned below or set weight to Relative Layout then replace it with Relative Layout
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
1.0f
);
YOUR_VIEW.setLayoutParams(param);
You can try this approach.
First, you get the LayoutParams associated with this Button. Perform a type conversion.
LinearLayout.LayoutParams linearLayoutParams = (LinearLayout.LayoutParams) button.getLayoutParams();
Then assign the required value of the "weight" parameter.
linearLayoutParams.weight = 5;
Redraw the layout.
button.requestLayout();

Categories

Resources