2010-05-13 14 views
5

我一直試圖在Android 1.5中創建一個複合控件(作爲described here),但無法找到任何有關如何使用XML實現此功能的好例子文件來指定佈局。我很好使用在構造函數如下創建活動,然後加載XML文件:基於LinearLayout創建自定義組件,以XML格式聲明佈局

setContentView(R.layout.main); 

不過,我想這樣做在的LinearLayout的子類 - 這樣我就可以用在其它XML這種化合物成分佈局。沿線的東西:

public class CustomView extends LinearLayout 
{ 
    public CustomView(Context context) { 
     super(context); 
     setupView(); 
    } 
    public CustomView(Context context, AttributeSet attrs) 
    { 
     super(context, attrs); 
     setupView(); 
    } 
    public void setupView() 
    { 
    setContentView(R.layout.custom); // Not possible 
    } 
} 

這樣做的正確方法是什麼?

回答

13

您有您的自定義視圖「膨脹」的佈局:

LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
layoutInflater.inflate(R.layout.custom, this, true); 
+0

所以我CustomView.java裏面我吹我想以某種方式將XML? – powerj1984 2011-05-13 14:41:47

+0

感謝這.... – Sid 2012-03-27 17:42:57