2012-04-05 77 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

相關問題