使用以下代码:
public class CustomView extends RelativeLayout {
public CustomView(Context context) {
this(context, null, 0);
}
public CustomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView();
}
private void initView() {
inflate(getContext(), R.layout.custom_view, this);
}
}
布局很简单:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_view_id"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f00"/>
hierarchyviewer
显示以下内容:
CustomView
层次结构没用,我想将其删除。
有没有办法创建一个自定义视图来扩展ViewGroup
而不添加额外的View
?
答案 0 :(得分:2)
如果您的CustomView已经是XML布局中的RelativeLayout,您只需删除带有“@ + id / custom_view_id”的RelativeLayout并使用标签作为父亲 这将使用CustomView合并子项而不使用额外的RelativeLayout。 CustomView将setBackgroundColor
public class CustomView extends RelativeLayout {
public CustomView(Context context) {
this(context, null, 0);
}
public CustomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView();
}
private void initView() {
setBackgroundColor(Color.parseColor("#f00"));
inflate(getContext(), R.layout.custom_view, this);
}}
并且布局xml文件将是:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<!-- children here -->
</merge>