3

这一直困扰着我一段时间,我的搜索都没有产生结果。如果我有一个自定义的 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 方法来解决这个问题很容易,但这对我来说似乎很笨拙。有没有更好的办法?

4

2 回答 2

1

您不能使用自己的参数定义构造函数,因为您的构造函数签名与 FrameLayout 自己的构造函数签名冲突,并且您不是在调用super(context, attrs, defStyle);,而是在调用super(context, attrs);此构造函数不完整的构造函数。

您必须完全按原样定义所有三个本机构造函数:

FrameLayout(Context context)
FrameLayout(Context context, AttributeSet attrs)
FrameLayout(Context context, AttributeSet attrs, int defStyle)

您可以做的是在 xml 中使用您自己的(自定义)属性,然后在 MyFrameLayout 的attrs对象中检索它们

于 2012-04-05T20:01:22.197 回答
0

如果自定义组件是通过 XML 文件或 inflate 方法膨胀的。您不要在构造中传递元素,因为这在 android 中不受支持。

于 2012-04-05T20:00:03.413 回答