这一直困扰着我一段时间,我的搜索没有取得任何结果。如果我有一个自定义的GUI元素,我可以使用一个LayoutInflater来充气它,因为我是一个普通的组件。通货膨胀调用导致对我的自定义GUI元素的构造函数的调用,并且一切都很好。Android:使用LayoutInflater.inflate将自定义参数传递给构造函数
但是,如果我想添加一个自定义参数到我的元素的构造函数呢?有没有一种方法可以在使用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方法,我之后打电话来解决这个问题布局通货膨胀,但对我来说这似乎很笨拙。有没有更好的办法?
Woops,我试图让我的代码尽可能简单来说明我的观点,忽略了包含重载的构造函数。我编辑了我的问题。 你能详细说明你的最后一句话吗? – ForeverWintr 2012-04-05 21:23:42
关于我的最后一句话,请阅读:http://kevindion.com/2011/01/custom-xml-attributes-for-android-widgets/ – waqaslam 2012-04-05 21:33:15
或http://devmaze.wordpress.com/2011/05/ 22/236/ – waqaslam 2012-04-05 21:34:24