Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android view layout_width - how to change programmatically?

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?

like image 298
Henley Avatar asked Apr 15 '12 03:04

Henley


3 Answers

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);
like image 163
jeet Avatar answered Oct 18 '22 19:10

jeet


Or simply:

view.getLayoutParams().width = 400;
view.requestLayout();
like image 13
M. Usman Khan Avatar answered Oct 18 '22 19:10

M. Usman Khan


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);
like image 10
Shankar Agarwal Avatar answered Oct 18 '22 20:10

Shankar Agarwal