2

I found the below documentation on how to set a customView. But when I change the id in my layout to "text1" and "icon", setText() and setIcon() do not work.

public TabLayout.Tab setCustomView (int layoutResId)

Set a custom view to be used for this tab.

If the inflated layout contains a TextView with an ID of text1 then that will be updated with the value given to setText(CharSequence). Similarly, if this layout contains an ImageView with ID icon then it will be updated with the value given to setIcon(Drawable).

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

Can anyone give me an example of how this works?

Java code:

    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");

Layout Code:

<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" />
Community
  • 1
  • 1
Meng Tim
  • 408
  • 1
  • 6
  • 19
  • 1
    Worth a read. [Difference between `@+id`, `@id` and `@android` in Android](http://android-wtf.com/2012/11/difference-between-at-plus-id-and-at-id-in-android/) – OneCricketeer Jan 20 '16 at 23:26
  • You could alternatively inflate a custom view that you manage yourself, take a look here for a complete implementation: http://stackoverflow.com/a/32547335/4409409 – Daniel Nugent Jan 21 '16 at 00:23

1 Answers1

6

You need to use the system Resource identifiers. That is, @android:id/text1 and @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" />

If you would need to reference these IDs in your code, they would be android.R.id.text1 and android.R.id.icon.

Mike M.
  • 38,532
  • 8
  • 99
  • 95
  • 1
    I found some more information on this, for anyone who's interested. http://developer.android.com/guide/topics/ui/declaring-layout.html#id – ddsnowboard Jan 20 '16 at 23:28