如何动态更改Viewpager选项卡的颜色?

3
如何改变Tab的颜色?当我点击/滑动到绿色或任何其他标签时,该标签的颜色应更改为相应的颜色,其余标签的颜色应更改为黑色。我该如何做到这一点?我正在使用Viewpager。
我尝试在onpagelistener中使用以下代码:
  if(position == 0) {
                   viewpager.getChildAt(position).setBackgroundColour(getResources().getcolor(R.color.red);
         }        
  else if(position == 1) { 
                   viewpager.getChildAt(position).setBackgroundColour(getResources().getcolor(R.color.green);
         }

但是上面的代码没有任何效果。
我正在使用这段代码:Android Viewpager教程 Androidhive 图片
3个回答

2

最终我解决了问题。感谢@Xcihnegn提供的想法。以下是解决方案:

/* For setting default selected tab */

    actionBar.setSelectedNavigationItem(0);
    actionBar.getTabAt(0).setCustomView(R.layout.fragmnt_red);  

    /**
     * on swiping the viewpager make respective tab selected
     * */
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {

    /*on changing the page make respected tab selected */           
            actionBar.setSelectedNavigationItem(position);

                if(position == 0)
                {

                    actionBar.getSelectedTab().setCustomView(R.layout.fragmnt_red);

                }else if(position == 1)
                {
                    actionBar.getSelectedTab().setCustomView(R.layout.fragmnt_orange);

                }else if(position == 2)
                {
                    actionBar.getSelectedTab().setCustomView(R.layout.fragmnt_green);
                }

            }

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });
}

@Override
public void onTabSelected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction fragmentTransaction) {
    viewPager.setCurrentItem(tab.getPosition());
}

当一个标签未被选中时,setCustomView(null)会将其布局更改回原始的黑色。因此,只有选定的标签会改变颜色。取消选择标签将使其布局恢复到原始形式。
@Override
public void onTabUnselected(ActionBar.Tab tab,     android.support.v4.app.FragmentTransaction fragmentTransaction) {

        if(tab.getPosition() == 0)
        {
            actionBar.getTabAt(0).setCustomView(null);

        }else if(tab.getPosition() == 1)
        {
            actionBar.getTabAt(1).setCustomView(null);

        }else if(tab.getPosition() == 2)
        {
            actionBar.getTabAt(2).setCustomView(null);
        }
    } 
}

为了在设置自定义视图时消除不必要的填充,我们应该在styles.xml中使用以下代码。
<style name="Custom.ActionBar.TabView.Empty" parent="@android:style/Widget.ActionBar.TabView">
    <item name="android:paddingLeft">0dp</item>
    <item name="android:paddingRight">0dp</item>
    <item name="android:background">#000000</item>
</style>

<style name="CustomActionbartab" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="actionBarTabStyle">@style/Custom.ActionBar.TabView.Empty</item>
    <item name="android:actionBarTabStyle">@style/Custom.ActionBar.TabView.Empty</item>
</style>

不要忘记在活动中的setcontentview之前添加此代码。
settheme(R.styles.CustomActionbartab);

自定义选项卡的布局。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@color/red">

<TextView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="RED"
    android:textStyle="bold"
    android:gravity="center"
    android:textColor="#ffffff"/>
</RelativeLayout>

0

我曾经遇到过类似的问题。在我的情况下,我想要在用户点击导航抽屉中的一个片段时更改操作栏的颜色。

这是我用来解决这个问题的代码。

由于你无法从片段中访问操作栏,所以你必须在主菜单中创建它。这是我使用的方法。

public void restoreActionBar(int parsedColor) {
        this.parsedColor = parsedColor;
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
        actionBar.setBackgroundDrawable(new ColorDrawable(parsedColor));

    } 

public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.main_activity_trekkly, menu);
            restoreActionBar(parsedColor);
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

现在在你继承片段的类中:

public void onAttach(Activity activity) {
            super.onAttach(activity);

            ((MainActivityTrekkly)activity).onSectionAttached(4);
            MainActivityTrekkly mA = ((MainActivityTrekkly)getActivity());

            mA.restoreActionBar(Color.parseColor("#028482"));
        }

我已经让导航抽屉运作了,所以您可能需要调整这段代码。

这有帮助吗?


抱歉,这不是我想要的。我想要改变选项卡(红色、绿色、橙色)的颜色,而不是操作栏的颜色。 - Sudheesh Mohan
我知道,不过我认为看到导航抽屉和选项卡都使用片段可能会有所帮助。 - unknown_seagull
我只想在点击选项卡时更改它们的颜色。 - Sudheesh Mohan

0

这里有一个教程在Android操作栏中设置选项卡样式。你可以选择你的父主题,如API>=3的Theme.Holo,或支持库V7的Theme.AppCompat等。

此外,对于<item name="android:background">,你可以将其设置为你创建的用于选项卡状态更改的选择器:

android:background="@drawable/selector_tab"

selector_tab 可以是这样的:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/pressed_color"
       android:state_pressed="true" />
    <item android:color="@color/selected_color"
       android:state_selected="true" /> 

    <item android:color="@color/normal_color" />
</selector>


[更新]

为了动态更改选项卡颜色,建议使用带有选项卡的自定义视图:

//your_custom_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  >


  <TextView
    android:id="@+id/tab_name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:maxLines="1" />

</LinearLayout>

LinearLayout customView = (LinearLayout) getLayoutInflater().inflate(R.layout.your_custom_tab, null);

在编程中,当向 ActionBar 添加选项卡时,请使用 setCustomeView(customView)。并且在您的选项卡/页面更改监听器中:

Tab selectedTab = yourActionBar.getSelectedTab();
View tabView = selectedTab.getCustomView();
tabView.setBackgroundColor(your_select_color);  


为了消除由自定义视图引起的选项卡周围可能存在的间隙,您可以设置选项卡样式:

<style name="ActionBarTabStyle" parent="@android:style/Widget.AppCompat.Light.ActionBar.TabView">
   <item name="android:paddingLeft">0dp</item>
   <item name="android:paddingRight">0dp</item>
   <item name="android:paddingTop">0dp</item>
   <item name="android:paddingBottom">0dp</item>
</style>

并相应地使用您的主题父级。

希望这有所帮助!


颜色已经改变,但是选项卡的右侧、顶部和左侧存在间隙。选项卡没有完全填满宽度。 - Sudheesh Mohan
现在间隙已经消失了,但制表符指示器也消失了。 :( - Sudheesh Mohan
你能否通过移除 paddingTop 进行测试? - Xcihnegn
你能否尝试使用所有填充0dp,我的意思是加上paddingTop paddingBottom - Xcihnegn
我在未选中的时候放置了 set customview(null)。因此,当标签未被选中时,它将恢复到其旧的黑色颜色。因此,只有选定的标签会改变其颜色。 - Sudheesh Mohan
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接