更新时间:2022-12-11 19:23:22
我还没有尝试过,但是我认为通过覆盖LayoutInflater.Factory
可以很干净地做到这一点.这样,您可以拦截需要将其他参数传递给其构造函数的视图的创建,然后让其余视图陷入默认的膨胀状态.
I haven't tried this, but I think it would be possible to do this fairly cleanly by overriding the LayoutInflater.Factory
. That way, you can intercept the creation of the views that need additional parameters passed to their constructors, and let the rest of them fall through to default inflation.
例如,在您的活动中,在增加视图层次结构之前:
For example, in your activity, before you inflate the view hierarchy:
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
MyInflaterFactory factory = new MyInflaterFactory();
// Pass information needed for custom view inflation to factory.
factory.setCustomValue(42);
inflater.setFactory(factory);
对于工厂的实施:
class MyInflaterFactory implements LayoutInflater.Factory {
public void setCustomValue(int val) {
mCustomVal = val;
}
@Override
public View onCreateView (String name, Context context, AttributeSet attrs) {
if (name.equals("com.package.ViewWithCustomCreation")) {
return new ViewWithCustomCreation(context, attrs, mCustomVal);
}
return null;
}
private int mCustomVal;
}