基于LinearLayout创建自定义组件,以XML格式声明布局

时间:2010-05-13 16:08:49

标签: java xml android layout

我一直在尝试在Android 1.5中创建一个复合控件(如described here)但是却找不到任何关于如何使用XML文件来指定布局的好例子。我可以创建一个Activity,然后在构造函数中使用以下代码加载一个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
  }
}

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:14)

您必须“夸大”自定义视图的布局:

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