0

I'm trying to create a tab layout with custom tabs in android:

FnBFragment.java:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_fnb, container, false);
    mTabs = (TabLayout) view.findViewById(R.id.tabs);
    Resources res = getResources();
    int customTabViewId = R.layout.fnb_tab_view;
    for (String category : categories) {
        TabLayout.Tab tab;
        View tabView = inflater.inflate(customTabViewId, container, false);
        tab = mTabs.newTab();
        tab.setCustomView(tabView);
        tab.setText("Hello"); // just for testing, should be category instead of "Hello"
        mTabs.addTab(tab);
    }
}

fnb_tab_view.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:textSize="20sp"
        android:textColor="@color/black"/>
</LinearLayout>

fragment_fnb.xml:

<android.support.design.widget.TabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.1" />

Here's the result:

enter image description here

As you can see there is no text in the tabs, even though the number of tabs seems to be correct. Am I doing something wrong? I heard that the TextView in the custom tab view with id text1 will be affected by the setText() call. Why doesn't this happen here?

Sahand
  • 7,980
  • 23
  • 69
  • 137
  • 1
    For `tab.setText()` to work, the `TextView` must have its ID as `android:id="@android:id/text1"`. Notice the `android:` prefix inside the quotes. – Mike M. Jul 18 '18 at 09:31
  • Thanks. But how is one supposed to understand this from the docs? It just says `text1`, nothing about any `android:` prefix. https://developer.android.com/reference/android/support/design/widget/TabLayout.Tab#setcustomview – Sahand Jul 18 '18 at 09:33
  • 1
    Um, experience, I guess? You're right that it's not very clear there, at all, but the `text1` link goes to the `android.R.id` page, so it follows that the ID is `android.R.id.text1`, which is `@android:id/text1` in XML. Whenever the platform docs mention/link a specific resource ID, you can pretty much bet that it's a system resource, so you'll need to use the `android` package name/namespace prefix appropriately. – Mike M. Jul 18 '18 at 09:38

0 Answers0