20

我有以下基于以下自定义视图RelativeLayout

public class LearningModeRadioButton extends
                                        RelativeLayout
                                     implements
                                        Checkable,
                                        View.OnClickListener {

    private void init(Context context, AttributeSet attrs) {
        LayoutInflater.from(context).inflate(R.layout.rb_learning_mode, this, true);
    }
}

R.layout.rb_learning_mode内容是:

<?xml version="1.0" encoding="utf-8"?>

<merge
        xmlns:android="http://schemas.android.com/apk/res/android"
        >

    <RadioButton
            android:id="@+id/rb"
            android:button="@drawable/sel_rb_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

    <TextView
            android:id="@+id/tv_mode_title"
            style="@style/text_regular"
            android:layout_toRightOf="@+id/rb"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />

    <TextView
            android:id="@+id/tv_description"
            style="@style/text_small"
            android:layout_below="@+id/tv_mode_title"
            android:layout_alignLeft="@+id/tv_mode_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />

</merge>

它有点工作,但布局参数(layout_xxx)被忽略了。我可以使用另一个<RelativeLayout/>作为布局的根元素,但我想避免在视图层次结构中有额外的级别。

所以问题是:如何使内部的布局属性<merge/>起作用?

4

2 回答 2

33

对于可能仍在为此苦苦挣扎的任何人,您应该parentTag在合并标签内指定属性。您还需要指定layout_heightlayout_width使其工作。

    <merge
        tools:parentTag="android.widget.RelativeLayout"
        tools:layout_width="match_parent"
        tools:layout_height="match_parent"
    >
    // Child Views
    </merge>

编辑器现在应该正确显示所有内容。

于 2017-12-09T06:23:33.410 回答
3

合并对 ​​LinearLayout 和 FrameLayout 有用,它不适合 RelativeLayout。

显然,在这种情况下使用是有效的,因为活动内容视图的父级始终是 FrameLayout。例如,如果您的布局使用 LinearLayout 作为其根标记,则无法应用此技巧。不过,这在其他情况下也很有用。

检查这个:

于 2013-05-29T13:09:14.533 回答