如何使用android.support.design.widget.TabLayout创建选项卡的自定义布局?

Men*_*Tim 2 android

我找到了以下关于如何设置的文档customView.但是当我将id我的布局更改为"text1"和"icon"时,setText()并且setIcon()不起作用.

public TabLayout.Tab setCustomView(int layoutResId)

设置要用于此选项卡的自定义视图.

如果膨胀的布局包含一个TextViewID为,text1那么将使用给定的值更新setText(CharSequence).同样,如果此布局包含ImageView带有ID的图标,则它将使用给定的值进行更新setIcon(Drawable).

(来源:http://developer.android.com/reference/android/support/design/widget/TabLayout.Tab.html#setCustomView(int))

谁能举个例子说明这是如何运作的?

Java代码:

    TabLayout.Tab tabAdd = tabLayout.getTabAt(0);
    tabAdd.setCustomView(R.layout.tab_layout_custom_view);
    tabAdd.setText("Add");
    tabAdd.setIcon(R.mipmap.add_tab).setText("Add");
Run Code Online (Sandbox Code Playgroud)

布局代码:

<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:id="@+id/icon"/>
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="0"
    android:id="@+id/text1"
    android:gravity="center"
    android:layout_below="@+id/icon" />
Run Code Online (Sandbox Code Playgroud)

Mik*_* M. 5

您需要使用系统资源标识符.那是,@android:id/text1@android:id/icon.

<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:id="@android:id/icon"/>
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="0"
    android:id="@android:id/text1"
    android:gravity="center"
    android:layout_below="@android:id/icon" />
Run Code Online (Sandbox Code Playgroud)

如果您需要在代码中引用这些ID,它们将是android.R.id.text1android.R.id.icon.