How to install the application: tabBackground tabLayout Programmatically?

This is my code: this is tabLayout, that I setupWithaViewpager

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif-light"
        app:tabPaddingEnd="-1dp"
        app:tabBackground="@drawable/tab_color_selector"
        app:tabPaddingStart="-1dp"
        app:tabTextAppearance="@style/MineCustomTabText" />

But how to install it programmatically?

 app:tabBackground="@drawable/tab_color_selector"

It is very important to set this tabBackground programmatically, because I want the color to change depending on the theme that the user has selected

This is what I already tried, but none of them work:

    tabLayout.setBackground(getResources().getDrawable(R.drawable.tab_color_selector));
    tabLayout.setBackgroundResource((R.drawable.tab_color_selector));
    tabLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.tab_color_selector));
    tabLayout.setBackground(ContextCompat.getDrawable(this, R.drawable.tab_color_selector));

Note:

This is my tab_color_selector.xml in drawable:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/white" android:state_selected="true" />
    <item android:drawable="@color/blue_alu" />
</selector>
+7
source share
7 answers

Try it.

ViewGroup tabStrip = (ViewGroup) tabLayout.getChildAt(0);
for (int i = 0; i < tabStrip.getChildCount(); i++) {
    View tabView = tabStrip.getChildAt(i);
    if (tabView != null) {
        int paddingStart = tabView.getPaddingStart();
        int paddingTop = tabView.getPaddingTop();
        int paddingEnd = tabView.getPaddingEnd();
        int paddingBottom = tabView.getPaddingBottom();
        ViewCompat.setBackground(tabView, AppCompatResources.getDrawable(tabView.getContext(), tabViewBgResId));
        ViewCompat.setPaddingRelative(tabView, paddingStart, paddingTop, paddingEnd, paddingBottom);
    }
}
+4
source

If you want to change the selected tab background, you can use this: (Set your custom view after setting the viewPager)

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);    
    tabLayout.setupWithViewPager(mViewPager);
    tabLayout.getTabAt(tabLayout.getSelectedTabPosition()).setCustomView(R.layout.your_layout);


If you want to change the background of tabLayout, use this:

TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setBackground(ContextCompat.getDrawable(this, R.drawable.your_drawable));

API > 21, ContextCompat :

tabLayout.setBackground(getDrawable(R.drawable.badge));

:

<android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:theme="@style/Toolbar"
        app:popupTheme="@style/Toolbar.Popup" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMaxWidth="0dp"
        app:tabGravity="fill"
        app:tabMode="fixed" />

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

Drawable

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="@color/red" />
</shape>
+2

, :

PagerAdapter

   fun initTabsView(parent: TabLayout) {
    val layoutInflater = LayoutInflater.from(parent.context)
    (0 until count).forEach { i ->
        val tab: TabLayout.Tab? = parent.getTabAt(i)
        tab?.customView = getTabView(layoutInflater, i)
    }
}

private fun getTabView(layoutInflater: LayoutInflater, position: Int): View {
    val binding = TabCasinoBinding.inflate(layoutInflater)
    binding.category = categories[position]
    return binding.root
}

initTabsView (parent: TabLayout), PagerAdapter

+1

"app:tabBackground="@drawable/tab_color_selector"", :

( tab_color_selector second_tab_color_selector ( )

XML TabLayout:

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabDots"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:tabBackground="@drawable/tab_color_selector"
        app:tabGravity="center"
        app:tabIndicatorHeight="0dp" />

onCreate:

tabLayout.setupWithViewPager(viewPagerFragments, true);
setupViewPager(viewPagerFragments);

TabLayoutOnPageChangeListener:

viewPagerFragments.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout) {

      @Override
      public void onPageSelected(int position) {
        switch (position) {
          case 0:
            //Here my background is white so I need grey dots
            tabLayout.getTabAt(position).setIcon(getResources().getDrawable(R.drawable.tab_color_selector));
            tabLayout.getTabAt(1).setIcon(getResources().getDrawable(R.drawable.tab_color_selector));
            tabLayout.getTabAt(2).setIcon(getResources().getDrawable(R.drawable.tab_color_selector));
            break;

          case 1:
            //Here my background is also white so I need grey dots
            tabLayout.getTabAt(0).setIcon(getResources().getDrawable(R.drawable.tab_color_selector));
            tabLayout.getTabAt(position).setIcon(getResources().getDrawable(R.drawable.tab_color_selector));
            tabLayout.getTabAt(2).setIcon(getResources().getDrawable(R.drawable.tab_color_selector));
            break;

          case 2:
            //Here my background is grey so I need white dots
            tabLayout.getTabAt(0).setIcon(getResources().getDrawable(R.drawable.second_tab_color_selector));
            tabLayout.getTabAt(1).setIcon(getResources().getDrawable(R.drawable.second_tab_color_selector));
            tabLayout.getTabAt(position).setIcon(getResources().getDrawable(R.drawable.second_tab_color_selector));
            break;
        }
      }

    });

"", , width (android:layout_width="50dp" TabLayout XML).

NPE tabLayout.getTabAt(X).setIcon(....), , , 3 , ... ( , for?)

, -

---EDIT 1---

API 28, 27 19, , API 27... - .

---EDIT 2---

... .

+1

:

Field field;
try {
    field = tabLayout.getClass().getDeclaredField("mTabBackgroundResId");
    field.setAccessible(true);
    field.set(tabLayout, R.drawable.tab_background);
} catch (NoSuchFieldException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
}
0

Try it like this: I had two types of background for the tab. Depending on the size of the account, it will change the result.

Field field;
    try {
        field = tabLayout.getClass().getDeclaredField("tabBackgroundResId");
        field.setAccessible(true);
        if(tabLayout.getTabCount()>=3){
            tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
            field.set(tabLayout, R.drawable.tab_color_selector_two);
        } else {
            field.set(tabLayout, R.drawable.tab_color_selector);
            tabLayout.setTabMode(TabLayout.MODE_FIXED);
        }
    } catch (NoSuchFieldException | IllegalAccessException e) {
        Logger.e("TabError",e.getMessage());
    }
0
source

First create a tab selector:

// Tab Selector

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/tab_indicator_selected" 
android:state_selected="true"></item>
<item android:drawable="@drawable/tab_indicator_default"></item>
</selector>

// tab_indicator_slected

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="0dp"
android:shape="ring"
android:thickness="4dp"

android:useLevel="false">

<solid android:color="@color/intro_pink"></solid>

// default tab indicator

<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="ring" android:innerRadius="0dp" 
android:thickness="4dp" android:useLevel="false"

xmlns:android="http://schemas.android.com/apk/res/android">

<solid android:color="@color/white"></solid>
</shape>

add your ViewPager with Layout Tab adapter to your layout

 <androidx.viewpager.widget.ViewPager
            android:id="@+id/vp_pager"
            android:layout_width="match_parent"
            android:layout_height="@dimen/standard_100"
            android:visibility="visible"></androidx.viewpager.widget.ViewPager>

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center|bottom"
            app:tabBackground="@drawable/tab_selector"
            app:tabGravity="center"
            app:tabIndicatorHeight="0dp">

        </com.google.android.material.tabs.TabLayout>

// onCreate

 @Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ViewPager vp = findViewById(R.id.vp_pager);
    TabLayout tb = findViewById(R.id.tab_layout);
    tb.setupWithViewPager(vp);

// add this only if tb.setupWithViewPager (vp) did not work perfectly

    vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                  tb.getTabAt(position).select();

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
}
-1
source

Source: https://habr.com/ru/post/1671150/


All Articles