通过从xml扩充来扩展RelativeLayout?

use*_*024 2 inheritance android relativelayout

我想创建一个名为TabView的类,它扩展RelativeLayout,并从包含RelativeLayout的xml中膨胀.问题是它似乎没有像我预期的那样工作.我在构造函数中做错了吗?我知道layoutInflater.inflate返回View对象但是我必须使它等于什么?任何建议都值得赞赏!

private class TabView extends RelativeLayout {
    private int mIndex;

    public TabView(Context context) {
        super(context, null, R.attr.vpiTabPageIndicatorStyle);
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        layoutInflater.inflate(R.layout.tabview_title_subtitle, null);
    }

    public int getIndex() {
        return mIndex;
    }

    public void setTitle() {
        TextView title = (TextView)findViewById(R.id.title);
        title.setText("Followers");
    }

    public void setSubitle() {
        TextView subtitle = (TextView)findViewById(R.id.subtitle);
        subtitle.setText("435");
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是tabview_title_subtitle.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Title"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/subtitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/title"
        android:text="Subtitle"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

Dmi*_*sev 8

首先,您的布局应如下所示:

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:text="Title"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/subtitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_below="@+id/title"
    android:text="Subtitle"
    android:textAppearance="?android:attr/textAppearanceMedium" />

</merge>
Run Code Online (Sandbox Code Playgroud)

RelativeLayout换句话说,你最终会得到另一个RelativeLayout

第二.像这样膨胀它:

layoutInflater.inflate(R.layout.tabview_title_subtitle, this);    
Run Code Online (Sandbox Code Playgroud)