代码之家  ›  专栏  ›  技术社区  ›  pheelicks

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

  •  6
  • pheelicks  · 技术社区  · 15 年前

    我一直在尝试在Android1.5中创建复合控件(如 described here )但是,在如何使用XML文件指定布局方面,还没有找到任何好的例子。我可以创建活动,然后使用构造函数中的以下内容加载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 回复  |  直到 14 年前
        1
  •  14
  •   Brandon O'Rourke    15 年前

    您必须为自定义视图“膨胀”布局:

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