82

This is my view, and I wish to change layout_width to "10dip". How do I do so programmatically? Note, this is not a LinearLayout, it's a View.

<View 
    android:id="@+id/nutrition_bar_filled" 
    android:background="@drawable/green_rectangle" 
    android:layout_height="30dp"
    android:layout_width="50dp"/>       

I know about LayoutParams. How do I use it to set the width to 10dip?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Henley
  • 21,258
  • 32
  • 119
  • 207

4 Answers4

186

I believe your question is to change only width of view dynamically, whereas above methods will change layout properties completely to new one, so I suggest to getLayoutParams() from view first, then set width on layoutParams, and finally set layoutParams to the view, so following below steps to do the same.

View view = findViewById(R.id.nutrition_bar_filled);
LayoutParams layoutParams = view.getLayoutParams();
layoutParams.width = newWidth;
view.setLayoutParams(layoutParams);
Community
  • 1
  • 1
jeet
  • 29,001
  • 6
  • 52
  • 53
13

Or simply:

view.getLayoutParams().width = 400;
view.requestLayout();
M. Usman Khan
  • 3,689
  • 1
  • 59
  • 69
10

try using

View view_instance = (View)findViewById(R.id.nutrition_bar_filled);
view_instance.setWidth(10);

use Layoutparams to do so where you can set width and height like below.

LayoutParams lp = new LayoutParams(10,LayoutParams.wrap_content);
View_instance.setLayoutParams(lp);
Shankar Agarwal
  • 34,573
  • 7
  • 66
  • 64
  • can you clarify? I'm almost ready to mark you as right answer. How do I get view_instance? – Henley Apr 15 '12 at 04:16
  • @Hisoka use `findViewById(R.id.nutrition_bar_filled)` to get the view – Chris Thompson Apr 15 '12 at 04:18
  • That's the first thing I tried. Seemed very intuitive, yet setWidth is not a valid function for a view. View filledBar = rowView.findViewById(R.id.nutrition_bar_filled); filledBar.setWidth(10) <-- not valid. – Henley Apr 15 '12 at 04:19
  • 3
    The method setWidth(int) is undefined for the type View – Henley Apr 15 '12 at 04:21
  • Ok, I refined my question. I already know about Layout params. My question is how do I use Layout Params to set the width of my View to "10dip". Reading the documentation online, it's not so obvious to me. – Henley Apr 15 '12 at 04:23
4

androidx (core-ktx) contains an extension function to update layout params, for example:

view.updateLayoutParams<ConstraintLayout.LayoutParams> {
    width = ConstraintLayout.LayoutParams.MATCH_PARENT
    // or wrap_content
    width = ConstraintLayout.LayoutParams.WRAP_CONTENT
    // or size measured in pixels
    width = 200 
}
Vladislav
  • 1,236
  • 13
  • 22