2010-05-13 61 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