【问题标题】:Create custom component based on LinearLayout, declaring layout in XML基于LinearLayout创建自定义组件,在XML中声明布局
【发布时间】:2011-02-19 04:17:29
【问题描述】:

我一直在尝试在 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
  }
}

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

【问题讨论】:

    标签: java xml android layout


    【解决方案1】:

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

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

    【讨论】:

    • 所以在我的 CustomView.java 中我以某种方式膨胀了我想要的 xml?
    猜你喜欢
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多