[英]Programmatically change View properies Android
In general, I'm trying to understand if it's possible in Android to arbitrarily change the properties of a view programmatically. 总的来说,我试图了解在Android中是否有可能以编程方式任意更改视图的属性。
I understand that there are many properties that can be changed via methods (eg TextView.setBackgroundColor() among many others) but there aren't methods for every possible property. 我知道可以通过方法(例如TextView.setBackgroundColor()等)来更改许多属性,但是并不是每种可能的属性都有方法。
Specifically, I'm interested in instantiating a custom View and then changing the layout_weight. 具体来说,我有兴趣实例化自定义视图,然后更改layout_weight。 I'm interested in learning how to do this, but in general I want to know how I'm supposed to create a custom View if I can't change it's properties programmatically.
我有兴趣学习如何执行此操作,但总的来说,我想知道如果无法以编程方式更改其属性,应该如何创建自定义视图。 I understand I can change all its properties in xml (including custom xml properties) but I want to be able to instantiate the view at run-time.
我知道我可以在xml中更改其所有属性(包括自定义xml属性),但是我希望能够在运行时实例化视图。
layout_
attributes are actually slightly different than most other things as explained in this pro-tip : they're instructions to the parent ViewGroup and are stored in their LayoutParams
. layout_
属性其实比在解释大多数其他的事情略有不同这个专业提示 :他们是父ViewGroup中的指令,并存储在他们LayoutParams
。
For example, layout_weight
in a LinearLayout
would be found in LinearLayout.LayoutParams . 例如,
layout_weight
在LinearLayout
会中找到LinearLayout.LayoutParams 。 This means you can change them by doing 这意味着您可以通过以下方式更改它们
LinearLayout.LayoutParams params =
(LinearLayout.LayoutParams) yourCustomView.getLayoutParams();
// Set the weight however you like
params.weight = 4.0f;
Creating the view allows you to do this as well: 创建视图还允许您执行以下操作:
LinearLayout parentLayout = ...;
YourCustomView yourCustomView = ...;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, // width
LayoutParams.WRAP_CONTENT, // height
1.0f); // weight
parentLayout.addView(yourCustomView, params);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.