user2522885
user2522885

Reputation: 615

Android ~ Why does FragmentPageAdapter clear my Layout's TabItem icon?

The following is within my main activity's layout file:

<android.support.design.widget.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="0dp"
    android:layout_height="39dp"
    android:layout_marginEnd="16dp"
    android:layout_marginTop="8dp"
    app:layout_constraintEnd_toStartOf="@+id/settingsButton"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:icon="@drawable/ic_mic_black_36dp" />

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:icon="@drawable/ic_folder_black_36dp" />

</android.support.design.widget.TabLayout>

If i do nothing but run my code containing the above the TabItem will show icons but the moment i set the TabLayout to have a FragmentPageAdapter the icons disappear leaving a blank space.

The following is my FragmentPageAdpater:

public class ViewPagerFragmentAdapter extends FragmentPagerAdapter
{
    private final List<Fragment> mFragmentList = new ArrayList<>();

    public ViewPagerFragmentAdapter(FragmentManager manager)
    {
        super(manager);
    }

    @Override
    public Fragment getItem(int position)
    {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount()
    {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment)
    {
        mFragmentList.add(fragment);
    }
}

Any ideas why when i go to tabLayout.setupWithViewPager(viewPager); the icons now disappear? I only show icons not text. There are only 2 fragments being added and so there are only 2 blank tabs being shown.

Upvotes: 0

Views: 89

Answers (2)

user2522885
user2522885

Reputation: 615

As a solution i decided to add the following into my main activity's onCreate()

tabLayout.setupWithViewPager(viewPager);

tabLayout.getTabAt(0).setIcon(R.drawable.ic_mic_black_36dp);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_folder_black_36dp);

The last 2 lines added the icons to my blank tabs. They must be applied AFTER the setupWithViewPager call.

Upvotes: 0

Ben P.
Ben P.

Reputation: 54234

TabLayout.setupWithViewPager() will eventually call through to TabLayout.populateFromPagerAdapter(), which in turn will call TabLayout.removeAllTabs(). After that, it will create new tabs using the ViewPager's page titles:

for (int i = 0; i < adapterCount; i++) {
    addTab(newTab().setText(mPagerAdapter.getPageTitle(i)), false);
}

As such, the <TabItem> tags in your layout are simply thrown away and replaced.

Upvotes: 0

Related Questions