如何设置app:tabBayground的tabLayout编程?

时间:2017-03-01 15:14:26

标签: android

这是我的代码:它是我setupWith Viewpager

的标签页
    <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" />

但是如何以编程方式设置?

 app:tabBackground="@drawable/tab_color_selector"

以编程方式设置此tabBackground非常重要,因为我希望颜色根据用户选择的主题而改变

这些是我已经尝试过的,但它们都没有起作用:

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

注意:

这是我在drawable中的tab_color_selector.xml:

<?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>

8 个答案:

答案 0 :(得分:3)

如果要更改选定的标签背景,可以使用: (设置viewPager后设置自定义视图)

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


如果要更改tabLayout背景,请使用:

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

如果您正在使用API​​级别&gt; 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>

<强>绘制对象

<?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>

答案 1 :(得分:2)

试试这个。

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

答案 2 :(得分:1)

仅对标签使用自定义布局,这是工作示例:

将这两种方法放入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
}

和要初始化PagerAdapter本身的initTabsView(父级:TabLayout)

答案 3 :(得分:1)

我做到了通过编程来更改“ app:tabBackground="@drawable/tab_color_selector"”:

(我的tab_color_selectorsecond_tab_color_selector就像您一样(一个选择器,其默认颜色为一个,所选择的颜色为一个)

TabLayout XML:

    <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(在TabLayout XML中设置为android:layout_width="50dp")。

我在所有tabLayout.getTabAt(X).setIcon(....)上都有NPE警告,但是因为我知道有3个标签,所以我允许自己执行此操作...(也许是使用for的更好的解决方案?)

希望这会对某人有所帮助

---编辑1 ---

我已经在API 28、27和19上进行了测试,但似乎无法在我的仿真器API 27上运行。...将在实际设备上尝试其他操作。

---编辑2 ---

来自Ankur的响应应该是可以接受的……在我所有的仿真器上都像魅力一样,而且速度更快。

答案 4 :(得分:1)

这是唯一对我有用的解决方案!!!

binding.tabs.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
    override fun onTabReselected(tab: TabLayout.Tab?) {}
    override fun onTabUnselected(tab: TabLayout.Tab?) {}


    override fun onTabSelected(tab: TabLayout.Tab?) {
     tab.view.background = ResourcesCompat.getDrawable(requireContext().resources,  R.drawable.tab_color_selector, null)
    }
}

答案 5 :(得分:0)

你可以这样做:

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();
}

答案 6 :(得分:0)

像这样尝试,我有两种背景布局。根据标签页数的大小,它将修改结果

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());
    }

答案 7 :(得分:-1)

首先创建一个标签选择器:

//选项卡选择器

<?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>

//选项卡指示器默认值

<?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>

在布局中添加带有Tab布局适配器的ViewPager

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

///仅在tb.setupWithViewPager(vp)不能完美运行时添加它

    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) {

            }
        });
}