我如何以编程方式更改我的动作栏的所选标签指示?我已经阅读了大约
tab styling和Tab.setCustomView()方法,但这些都没有帮助:
>使用选项卡样式,我可以更改指示器颜色,但它将保留所有选项卡(我想为每个选项卡指定一个).
>使用选项卡自定义视图,我已经使用了带有TextView的选项卡标题的布局,以及用于管理指示器颜色的View.在java中,我动态地更改View的背景,但是问题在于View的背景与选项卡界限不匹配.
<TextView android:id="@+id/custom_tab_text" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerInParent="true" android:layout_centerHorizontal="true" android:gravity="center|center_horizontal" android:textStyle="bold"/> <View android:id="@+id/custom_tab_view" android:layout_width="match_parent" android:layout_height="10dp" android:layout_alignParentBottom="true"/>
有人可以告诉我我哪里错了吗?还有另一种做法吗?谢谢
解决方法
我已经成功地使用@ Padma的答案来实现我想要的生成我的标签指示器背景:我需要5个选择器:绿色,黄色,蓝色,橙色和红色.所以我创建了5个xml可绘图(tabs_selector_red.xml,tabs_selector_blue.xml等):
tabs_selector_green.xml:
<!-- Non focused states --> <item android:drawable="@android:color/transparent" android:state_focused="false" android:state_pressed="false" android:state_selected="false"/> <item android:drawable="@drawable/layer_bg_selected_tabs_green" android:state_focused="false" android:state_pressed="false" android:state_selected="true"/> <!-- Focused states --> <item android:drawable="@android:color/transparent" android:state_focused="true" android:state_pressed="false" android:state_selected="false"/> <item android:drawable="@drawable/layer_bg_selected_tabs_green" android:state_focused="true" android:state_pressed="false" android:state_selected="true"/> <!-- Pressed --> <!-- Non focused states --> <item android:drawable="@android:color/transparent" android:state_focused="false" android:state_pressed="true" android:state_selected="false"/> <item android:drawable="@drawable/layer_bg_selected_tabs_green" android:state_focused="false" android:state_pressed="true" android:state_selected="true"/> <!-- Focused states --> <item android:drawable="@android:color/transparent" android:state_focused="true" android:state_pressed="true" android:state_selected="false"/> <item android:drawable="@drawable/layer_bg_selected_tabs_green" android:state_focused="true" android:state_pressed="true" android:state_selected="true"/>
我还为每个xml背景创建了一个图层列表:
layer_bg_selected_tabs_green.xml
<item> <shape android:shape="rectangle" > <solid android:color="@color/tab_green" /> <padding android:bottom="5dp" /> </shape> </item> <item> <shape android:shape="rectangle" > <solid android:color="#FFFFFF" /> </shape> </item>
最后,在Java中,我使用选择的标签的自定义视图和索引动态购买背景:
private static final int[] TABS_BACKGROUND = { R.drawable.tabs_selector_orange,R.drawable.tabs_selector_green,R.drawable.tabs_selector_red,R.drawable.tabs_selector_blue,R.drawable.tabs_selector_yellow }; /* BLA BLA BLA */ @Override public void onTabSelected(Tab tab,FragmentTransaction ft) { // TODO Auto-generated method stub RelativeLayout tabLayout = (RelativeLayout) tab.getCustomView(); tabLayout.setBackgroundResource(TABS_BACKGROUND[tab.getPosition()]); tab.setCustomView(tabLayout); /* ... */ }
现在我们来添加一些截图: