Android 视图 layout_width - 如何以编程方式更改?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10159372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android view layout_width - how to change programmatically?
提问by Henley Chiu
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.
这是我的观点,我希望将 layout_width 更改为“10dip”。我如何以编程方式执行此操作?注意,这不是一个 LinearLayout,它是一个视图。
<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?
我知道 LayoutParams。我如何使用它来将宽度设置为 10dip?
回答by jeet
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.
我相信您的问题是仅动态更改视图的宽度,而上述方法会将布局属性完全更改为新的,因此我建议首先从视图中获取布局参数(),然后在 layoutParams 上设置宽度,最后将 layoutParams 设置为视图,所以按照下面的步骤来做同样的事情。
View view = findViewById(R.id.nutrition_bar_filled);
LayoutParams layoutParams = view.getLayoutParams();
layoutParams.width = newWidth;
view.setLayoutParams(layoutParams);
回答by Shankar Agarwal
You can set height and width like this also:
您也可以像这样设置高度和宽度:
viewinstance.setLayoutParams(new LayoutParams(width, height));
回答by Shankar Agarwal
try using
尝试使用
View view_instance = (View)findViewById(R.id.nutrition_bar_filled);
view_instance.setWidth(10);
use Layoutparamsto do so where you can set width and height like below.
使用Layoutparams来设置宽度和高度,如下所示。
LayoutParams lp = new LayoutParams(10,LayoutParams.wrap_content);
View_instance.setLayoutParams(lp);
回答by M. Usman Khan
Or simply:
或者干脆:
view.getLayoutParams().width = 400;
view.requestLayout();