【问题标题】:How to change background color of Tablayout from a fragment?如何从片段更改 Tablayout 的背景颜色?
【发布时间】:2021-08-31 21:35:21
【问题描述】:

我在 MainActivity 中创建了一个 tablayout,并使用 viewpager 创建了一堆片段。 当我单击片段中存在的按钮时,我想更改 tablayout 的颜色。 那么如何引用在 MainActivity 中创建的 tablayout 以便我可以在各个片段中更改它的颜色呢?

【问题讨论】:

  • 我会说创建方法来更改 MainActivity 中的选项卡颜色。然后在 Fragments 中创建嵌套接口,并在 MainActivty 中实现这些接口。检查此链接以获取有关片段 -> 活动之间通信的更多信息。 stackoverflow.com/questions/14247954/…

标签: android android-layout android-fragments android-tablayout


【解决方案1】:

您可以根据选项卡的位置使用tablyoutaddOnTabSelectedListener 更改选项卡布局的背景颜色,如下面的代码:

     tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    viewPager.setCurrentItem(tab.getPosition());
                    switch (tab.getPosition()){
// Change color of tab layout according to tab position
 
                        case 0:
                            tabLayout.setBackgroundColor(getResources().getColor(R.color.black));
                            break;
                        case 1:
                            tabLayout.setBackgroundColor(getResources().getColor(R.color.teal_200));
                            break;
                        default:
                            tabLayout.setBackgroundColor(getResources().getColor(R.color.black));
                            break;
    
                    }
                }
    
                @Override
                public void onTabUnselected(TabLayout.Tab tab) {
    
                }
    
                @Override
                public void onTabReselected(TabLayout.Tab tab) {
    
                }
            });

【讨论】:

    猜你喜欢
    • 2012-07-26
    • 2018-04-28
    • 2023-03-07
    • 2013-04-27
    • 2019-01-16
    • 1970-01-01
    • 2017-11-17
    • 2011-11-11
    • 1970-01-01
    相关资源
    最近更新 更多