如何基于xml布局编写自定义View类

时间:2012-11-23 13:31:05

标签: android android-layout android-custom-view

我有一个xml布局,其RelativeLayout可容纳4-5个子视图。我希望有一个基于此xml布局的自定义View类,并带有自定义onclick列表器。

我通过扩展RelativeLayout并将View作为成员来尝试使用自定义类。在我的构造函数中,我正在膨胀布局并将其分配给我的View成员。但我想让类本身与我的膨胀视图对象类似。 (我有没有意义!!)

我目前的代码类似于以下内容:

public class CustomItemView extends RelativeLayout {
  private Context context;
  private View itemView;

  public CustomItemView(Context context) {
    super(context);
    this.context = context;

     LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

      itemView = inflater.inflate(layout, null);                
  }

  public View getView() {
    return itemView;
  }       
}

1 个答案:

答案 0 :(得分:4)

实现它的一个简单方法是扩展FrameLayout并将膨胀的布局附加到构造函数中的自己(this):

public class MyView extends FrameLayout {

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.my_view, this);
    }

    // Your view logic here
}

然后您可以以编程方式使用全新视图:

MyView myView = new MyView(context);

或者在XML布局中:

<packageName.MyView
    android:layout_width="match_parent"
    android:layout_height="match_parent" />