gpt4 book ai didi

Android:使用 LayoutInflater.inflate 将自定义参数传递给构造函数

转载 作者:行者123 更新时间:2023-12-01 22:29:29 24 4
gpt4 key购买 nike

这已经困扰我一段时间了,我的搜索都没有产生结果。如果我有一个自定义 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>

和一个 inflater 调用:

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 方法来解决这个问题很容易,我在布局膨胀后立即调用该方法,但这对我来说似乎很笨拙。有更好的办法吗?

最佳答案

您不能使用自己的参数定义构造函数,因为您的构造函数签名与 FrameLayout 自己的构造函数签名冲突,并且您没有调用 super(context, attrs, defStyle);,而是调用 super(context, attrs); 对于这个构造函数来说是不完整的。

您必须需要完全按照原样定义所有三个 native 构造函数:

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

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

关于Android:使用 LayoutInflater.inflate 将自定义参数传递给构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10034430/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com