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

Ven*_*ana 1 android android-custom-view android-layout

我有一个包含 4-5 个子视图的 RelativeLayout 的 xml 布局。我想有一个基于此 xml 布局的自定义 View 类和一个自定义的 onclick 监听器。

我尝试通过扩展 RelativeLayout 并将视图作为成员来使用自定义类。在我的构造函数中,我正在膨胀布局并将其分配给我的 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;
  }       
}
Run Code Online (Sandbox Code Playgroud)

sda*_*bet 5

实现它的一种简单方法是在构造函数中扩展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
}
Run Code Online (Sandbox Code Playgroud)

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

MyView myView = new MyView(context);
Run Code Online (Sandbox Code Playgroud)

或者在 XML 布局中:

<packageName.MyView
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
Run Code Online (Sandbox Code Playgroud)