如何以编程方式设置View
中可在onCreate()
中使用的值?属性只能在XML中设置,成员值只能在View
充气(并且onCreate()
已经调用)之后才能设置。
在充气之前,我需要调用View
构造函数并设置成员值吗?还是有更好的方法?
发布于 2018-01-17 20:25:25
如果使用Context.getLayoutInflater().createView()
膨胀视图,则可以使用最后一个参数以编程方式将自定义属性传递给该视图。
编辑
为了同时使用来自xml的属性和编程属性,您必须实现一个定制的LayoutInflater。然而,因为
您可以看到自定义布局在Android Rec库中的示例。
您可以在此AttributeSet中看到自定义所以回答的示例。
自定义AttriuteSet
如果我将所有这些答案结合起来,您将得到您想要的东西,但是它将需要一些样板代码,因为AttributeSet
并不真正适合在动态中添加params。因此,您必须实现AttributeSet
(这是一个接口),它在构造函数中获取原始的AttributeSet
,并包装其所有功能,并以编程方式返回要添加的参数的正确值。
然后你就可以做这样的事情:
private static class MyLayoutInflater implements LayoutInflater.Factory {
private LayoutInflater other;
MyLayoutInflater(LayoutInflater other) {
this.other = other;
}
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
if (name.equals("MyView")) {
attrs = MyAttributeSet(attrs);
}
try {
return other.createView(name, "", attrs);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
private static class MyAttributeSet implements AttributeSet {
private AttributeSet other;
MyAttributeSet(AttributeSet other) {
this.other = other;
}
< More implementations ...>
}
@Override
protected void onCreate(Bundle savedInstanceState){
getLayoutInflater().setFactory(new MyLayoutInflater(getLayoutInflater());
getLayoutInflater().inflate(...)
}
这可能有效,但可能有更好的方法来实现你想要的。
添加自定义参数
您可以实现一个自定义的布局充气器,它将在返回视图之前设置一些参数,因此在视图上调用onCreate
之前将添加这些参数。所以会是这样的:
@Override
protected void onCreate(Bundle savedInstanceState){
getLayoutInflater().setFactory(new LayoutInflater.Factory() {
public View onCreateView(String name, Context context, AttributeSet attrs) {
if (name.equals("MyView")) {
View myView = myView(context, attrs); // To get properties from attrs
myView.setCustomParams(SomeCustomParam);
return myView;
} else {
return null;
}
}
});
getLayoutInflater().inflate(...)
}
https://stackoverflow.com/questions/48313734
复制