這一直困擾着我一段時間,我的搜索沒有取得任何結果。如果我有一個自定義的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