2012-04-05 74 views
1

这一直困扰着我一段时间,我的搜索没有取得任何结果。如果我有一个自定义的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方法,我之后打电话来解决这个问题布局通货膨胀,但对我来说这似乎很笨拙。有没有更好的办法?

回答

0

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

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检索它们对象

+0

Woops,我试图让我的代码尽可能简单来说明我的观点,忽略了包含重载的构造函数。我编辑了我的问题。 你能详细说明你的最后一句话吗? – ForeverWintr 2012-04-05 21:23:42

+0

关于我的最后一句话,请阅读:http://kevindion.com/2011/01/custom-xml-attributes-for-android-widgets/ – waqaslam 2012-04-05 21:33:15

+0

或http://devmaze.wordpress.com/2011/05/ 22/236/ – waqaslam 2012-04-05 21:34:24

相关问题