Setting LayoutParams with few Lines of Code - android

Is there an easy and simple way to set LayoutParams ? Or to be exactly, the MarginLayoutParams? I want to set the MarginRight to a few dp, unfortunately im not able to set these in the LayoutFile cause the Target is a ListFragment and in Code-Behind looks it very ugly.
The reason i do this not in the Layout of the items is so the code is optimized and perfomant.
To sum up: Is there any very simple and clean way to set Params ?

Yes, you can do something like this:
MyImageView i2 = new MyImageView(context);
LayoutParams lp = new LayoutParams(300, 300);
lp.LeftMargin = 100;
lp.TopMargin = 100;
lp.Gravity = 0;
this.AddView(i2, lp);

LayoutParams lp = new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT );
lp.setMargins( left, top, right, bottom );
You might need to write it as LinearLayout.LayoutParams, depending on what type of layout is the container.
And then you call the method setLayoutParams( lp ); on the given view/layout/widget.

Related

change position of views

i use this code to change the position of my view
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)myview.getLayoutParams();
params.topMargin = topmargin;
params.leftMargin = leftmargin;
myview.setLayoutParams(params);
and nothing change.but when i use this code
myview.setTop(topmargin);
myview.setLeft(leftmargin);
it will work.now i want to know what is wrong with my first code??
because in the internet so many people suggest first code to change the position of views.
EDIT
also this code doesn't work
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)myview.getLayoutParams();
params.setMargins(100,100,0,0);
myview.setLayoutParams(params);
myview.requestLayout();
thanks in advance
Try calling myview.requestLayout(); after myview.setLayoutParams(params);
UPDATE
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)myview.getLayoutParams();
params.setMargins(left,top, right,bottom);
myview.setLayoutParams(params);
myview.requestLayout();
You need to call requestLayout() after updating the layout params
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)myview.getLayoutParams();
params.topMargin = topmargin;
params.leftMargin = leftmargin;
myview.setLayoutParams(params);
myview.requestLayout();
And this is a brief explanation from official documentation:
.setTop() ( same with .setLeft() )
Sets the top position of this view relative to its parent. This method
is meant to be called by the layout system and should not generally be
called otherwise, because the property may be changed at any time by
the layout.
topMargin ( same with leftMargin )
The top margin in pixels of the child. Margin values should be
positive. Call setLayoutParams(LayoutParams) after reassigning a new
value to this field.

Programmatically set button width to 50% of parent LinearLayout

I created a Dialog using LinearLayout and in this Dialog, I have a Button. I want to set its width to 50% of the Dialog's width, but no matter what I do, the button is still filling the entire width. The main problem seems to be that I cannot set the button's weight programmatically. I tried creating a second horizontal LinearLayout that would hold the button with weight set to 0.5f (the parent has a weightSum of 1), but that did not change anything. How can I set the button to be half the width?
I've looked at all the other questions but most of them were using xml so they were not relevant, and the one that solved it programmatically was using hardcoded values in pixels which is obviously an incorrect solution to the problem.
EDIT: Adding some code
LinearLayout linearLayout = new LinearLayout(mContext);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setWeightSum(1);
// I use these params when I call addContentView
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
testButton = new Button(mContext);
testButton.setText("Test");
testButton.setId(1);
testButton.setWidth(0);
testButton.setGravity(Gravity.CENTER);
LinearLayout buttonLayout = new LinearLayout(mContext);
butonLayout.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.5f);
testButton.setLayoutParams(buttonParams);
buttonLayout.addView(testButton);
linearLayout.addView(buttonLayout);
...
this.addContentView(scrollView, layoutParams);
As I tried more and more options, the code became a mess. I decided to start from scratch and this code worked in the end:
LinearLayout forButton = new LinearLayout(mContext);
forButton.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams forButtonParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
forButton.setGravity(Gravity.CENTER);
DisplayMetrics dm = new DisplayMetrics();
this.getWindow().getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
forButton.addView(testButton);
testButton.getLayoutParams().width = width/2;
Are you setting the width value to 0dp as well? This is required for the layout engine to automatically to use layout weight respectively.
Edit
I think this line will get you the results you are looking for:
LayoutParams buttonParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 0.5f);
To find dialog width
DisplayMetrics dm = new DisplayMetrics();
dialog.getWindow().getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels ;
To Set Value programmatically
final LayoutParams lparams = new LayoutParams(Height,width/2); // Width , height
final Button button = new Button(this);
button.setLayoutParams(lparams);
EDIT
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(alertDialog.getWindow().getAttributes());
lp.width = 200;
lp.height = 200;
alertDialog.getWindow().setAttributes(lp);

How to set a button's parameters programmatically

I'm trying to add a bunch of buttons to a layout like this:
for( int i = 0; i < 10; i++ ) {
Button button = new Button( this );
button.setText( "" + i );
( ( LinearLayout )dialog.findViewById( R.id.Buttons ) ).addView( button );
}
My problem is how do I do this programmatically to all the buttons:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="32dip" />
I've been looking at LayoutParams but it doesn't look complete. Like how do I set the textSize to 32 dip?
Set your attributes using the following code:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
button.setLayoutParams(params);
button.setGravity(Gravity.CENTER_HORIZONTAL);
button.setTextSize(32);
If you want to specify the text size units use:
button.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 32);
LayoutParams relates to the parent ViewGroup which will contain the view. So in your case it's a LinearLayout so you need to create parameters for that one. Here's what I'm talking about:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.weight = 1f;
Button button = new Button(this);
button.setLayoutParams(lp);
button.setText("" + i);
((LinearLayout)dialog.findViewById(R.id.Buttons)).addView(button);
Use LayoutParams for the height, width and gravity with
LinearLayout.LayoutParams (int width, int height)
where you can use WRAP_CONTENT for the ints.
Then there are Button.setGravity() and Button.setTextSize() for the last two.
Hope this helps.
You'd use a LayoutParams object for the layout settings, and to set the text size use setTextSize() from the Button class.
You can set the gravity with setGravity() too.
TextSize is not inside Layout params. To set textSize you have to
button.setTextSize(32);

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