簡體   English   中英

如何以編程方式更改選項卡指示器顏色

[英]How to change Tab Indicator color programmatically

我是Android的新手 ,在開始編程之前我發現現在很多應用程序都在使用Fragments,特別是帶有Swipeable Views的Tab

如何更改選項卡指示器/突出顯示顏色 (我用Google搜索並將ActionBar顏色更改為RED編程),但不知道如何將選項卡指示器顏色更改為紅色。 (以編程方式優先)

我的ActionBar看起來像這樣

我使用下面的行來改變ActionBar的背景顏色 ,但我還需要以編程方式更改Tab Indicator的顏色。

actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.RED));

您可以通過創建自定義選項卡指示器視圖並使用setIndicator為選項卡實現不同的不同指示器來實現。

你想要連鎖

setIcon(R.drawable.ic_icon_name_here)

為您的標簽提供圖標

對於要使用自定義樣式的選項卡顏色,有關這些解決方案的更多信息,請查看如何更改Android選項卡窗口小部件的背景?

改變選擇器顏色的唯一方法是使用樣式(我看到“請注意”,順便說一句)。

drawable文件夾中創建tab_selector.xml並執行以下操作:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:drawable="@drawable/tab_selected_pink" />
    <item android:state_selected="false" android:drawable="@drawable/tab_unselected_white" />
</selector>

然后在你的values/styles.xml我想,做這樣的事情:

<style name="AppTheme" parent="Theme.AppCompat.Light">
     <item name="android:actionBarTabBarStyle">@style/MyTabStyle</item>
</style>

<style name="MyTabStyle" parent="android:Widget.ActionBar.TabBar">
    <item name="android:background">@drawable/tab_indicator_selector</item>
</style>

我可能錯誤的第一個樣式中的item name attribute和第二個樣式中的parent attribute 但總的來說,它看起來會像這樣。

你可以看到它很容易做到。 如果你想支持不同的屏幕,你真正需要做的就是制作9patch drawables。

您還可以查看Jake Wharton的ViewPagerIndicator ,這是使用任何導航模式最靈活的方式。

如果您知道有多少個選項卡,則可以很容易地以編程方式為每個選項卡或僅少數選項卡更改圖標顏色。

您需要做的就是復制用於選項卡的現有可繪制文件,為其命名,然后更改其中的顏色。

然后,您需要做的就是獲取每個選項卡並設置您希望用作圖標的drawable。

tabLayout.setupWithViewPager(pager, true);
tabLayout.getTabAt(0).setIcon(R.drawable.tab_color_grey);
tabLayout.getTabAt(1).setIcon(R.drawable.tab_color_black);
tabLayout.getTabAt(2).setIcon(R.drawable.tab_color_black);
tabLayout.getTabAt(3).setIcon(R.drawable.tab_color_black);
tabLayout.getTabAt(4).setIcon(R.drawable.tab_color_gold);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM