Android的观点layout_width - 如何以编程方式改变?观点、方式、Android、layout_width

2023-09-03 21:22:50 作者:泪落成霜不知寒

这是我的看法,我希望layout_width变为10dip。我该怎么做这样编程? 请注意,这不是一个线性布局,这是一个观点。

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

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

我知道的LayoutParams。我如何使用它来设置宽度为10dip?

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

推荐答案

我相信你的问题是动态变化的观点仅宽度,而上面的方法将彻底改变布局属性为新的,所以我建议getLayoutParams从视图中第一,然后将宽度上layoutParmas,最后设置的LayoutParams到视图,所以按照以下步骤来执行相同

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 layoutParmas, and finally set layoutparams to the view, so following below steps to do the same.

View view_instance = (View)findViewById(R.id.nutrition_bar_filled);
LayoutParams params=view_instance.getLayoutParams();
params.width=newOne;
view_instance.setLayoutParams(params);