如何以View编程方式设置可以在其中使用的值onCreate()?属性只能在 XML 中设置,成员值只能在View膨胀(并且onCreate()已经调用)之后设置。
我需要View在膨胀之前调用构造函数并设置成员值吗?或者,还有更好的方法?
如何以View编程方式设置可以在其中使用的值onCreate()?属性只能在 XML 中设置,成员值只能在View膨胀(并且onCreate()已经调用)之后设置。
我需要View在膨胀之前调用构造函数并设置成员值吗?或者,还有更好的方法?
如果您使用 膨胀视图Context.getLayoutInflater().createView(),则可以使用最后一个参数以编程方式将自定义属性传递给该视图
编辑
为了同时使用来自 xml 和以编程方式的属性,您必须实现一个自定义 LayoutInflater。然而,由于
您可以在 Android Rec Library中看到自定义布局的示例。
您可以在此SO answer中看到自定义 AttributeSet 的示例。
自定义属性集
如果我结合所有这些答案,你会得到你想要的,但它需要一些样板代码,因为AttributeSet它并不适合即时添加参数。因此,您必须实现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(...)
}
它可能有效,但可能有更好的方法来实现您想要的。
添加自定义参数
您可以实现一个自定义 layoutinflater,它将在返回视图之前设置一些参数,因此这些参数将在视图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(...)
}