这一直困扰着我一段时间,我的搜索都没有产生结果。如果我有一个自定义的 GUI 元素,我可以像使用普通组件一样使用 LayoutInflater 对其进行充气。通货膨胀调用导致调用我的自定义 GUI 元素的构造函数,一切都很好。
但是,如果我想在元素的构造函数中添加自定义参数怎么办?有没有办法可以在使用 LayoutInflater 时传递这个参数?
例如:
在主 xml 中,我的布局有一个支架:
<LinearLayout
android:id="@+id/myFrameLayoutHolder"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
和一个 MyFrameLayout.xml 文件:
<com.example.MyFrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/MyFLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1 >
<!-- Cool custom stuff -->
</com.example.MyFrameLayout>
和一个充气电话:
LayoutInflater MyInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout myFLayoutHolder = (LinearLayout) findViewById(R.id.myFrameLayoutHolder);
MyFrameLayout L = ((MyFrameLayout) MyInflater.inflate(R.layout.MyFLayout, myFLayoutHolder, false));
myFLayoutHolder.addView(L);
如果在扩展 FrameLayout 的类中,我向构造函数添加了一个参数,我会崩溃:
public class MyFrameLayout extends FrameLayout {
private int myInt;
public MyFrameLayout(Context context) {
this(context, null);
}
public MyFrameLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0, 0);
}
public MyFrameLayout(Context context, AttributeSet attrs, int defStyle, int myParameter) {
super(context, attrs, defStyle);
myInt = myParameter;
//Amazing feats of initialization
}
}
现在,通过定义我在布局膨胀后立即调用的自定义 init 方法来解决这个问题很容易,但这对我来说似乎很笨拙。有没有更好的办法?