AndroidWonderer
AndroidWonderer

Reputation: 145

Android TabLayout tab icons

I have the following code to set android TabLayout texts and images:

//First tab - Home Facebook Updates
        tabLayout.addTab(tabLayout.newTab()
                .setText("Tab 1")
                .setIcon(R.drawable.fb_updates));
        //Second tab - Instagram Latest Checkins
        tabLayout.addTab(tabLayout.newTab()
                .setText(Tab 2"));
                .setIcon(R.drawable.ic_location_on_white_24dp));
        //Third tab - Events
    tabLayout.addTab(tabLayout.newTab()
            .setText("אירועים")
            .setIcon(R.drawable.ic_event_note_white_24dp));

The code works great but for some reasons the tab icon appears ABOVE the tab text, instead of near the text. For example:

Tab 1 IMAGE

Tab 1 text

I need it to appeaer this way:

Tab 1 Image Tab 1 Text

Upvotes: 2

Views: 1351

Answers (1)

JoeyJubb
JoeyJubb

Reputation: 2321

The default tab layout will place the icon above the text. If you want the icon to the side, you'll have to provide a custom layout.

Note: don't give the ImageView the id android.R.id.icon because the tab layout will put a margin underneath it automatically, wherever it is!

Do something like this:

View tabView = LayoutInflater.from(context).inflate(R.layout.custom_tab, null, false);
// use findViewById etc to set the text and images
tabLayout.addTab(
    tabLayout.newTab()
    .setCustomView(tabView )
);

R.layout.custom_tab can be anything you like, but is most likely going to be something like:

<LinearLayout xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    tools:ignore="UseCompoundDrawables">

    <ImageView
        android:layout_width="@dimen/indicator_size_tab"
        android:layout_height="@dimen/indicator_size_tab"
        android:id="@+id/tab_icon"
        android:layout_marginRight="@dimen/margin_small"
        android:layout_marginEnd="@dimen/margin_small"/>

    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:id="@android:id/text1"
        android:textAppearance="@style/TextAppearance.Design.Tab"
        android:textColor="@color/tab_text"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:maxLines="2"/>

</LinearLayout>

Upvotes: 3

Related Questions