我在我的应用程序中使用TabLayout
进行选项卡式导航。我有一个非常奇怪的问题,我使用此代码创建了4个选项卡:
private int[] tabIcons = {R.drawable.navigation_timeline_icon_selector, R.drawable.navigation_feed_icon_selector,
R.drawable.navigation_messages_icon_selector, R.drawable.navigation_notification_icon_selector};
TabLayout tabLayout = setTabLayout();
if (tabLayout != null) {
for (int i = 0; i < 4; i++) {
tabLayout.getTabAt(i).setIcon(tabIcons[i]);
}
}
tabIcon中的每个项目都是具有选定和未选中状态的selector
。所有图标选择器配置如下:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/navigation_timeline_selected_icon" android:state_selected="true"/>
<item android:drawable="@drawable/navigation_timeline_selected_icon" android:state_pressed="true"/>
<item android:drawable="@drawable/navigation_timeline_icon" />
</selector>
问题是当应用程序启动时,第一个选定的选项卡(索引0)不使用选定的状态图标。相反,它使用非选择状态。
更详细的解释是这个问题的截图,首次启动我的选项卡如下所示:
相反,它应该是这样的:
更改页面后,所有图标都恢复为完整功能,并且正确选择了所选状态。
我尝试使用TabLayout.Tab select()
方法,但结果与使用的图标相同是未选择的图标。
有人知道我能做些什么来解决它吗?
试试这个:
tabLayout.getTabAt(yourInitialPosition).getCustomView().setSelected(true);
我在tabLayout中使用了xml选择器,用于具有以下状态的图标:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/icon_ajuda_off"/>
<item android:state_focused="false" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/icon_ajuda_on"/>
<item android:state_selected="false" android:state_pressed="true" android:drawable="@drawable/icon_ajuda_on"/>
<item android:state_selected="true" android:state_pressed="true" android:drawable="@drawable/icon_ajuda_on"/>
并在代码中:
private int[] tabIcons = {R.drawable.ic_tab_sites, R.drawable.ic_tab_help,
R.drawable.ic_tab_profile, R.drawable.ic_tab_notification, R.drawable.ic_tab_search};
if (tabLayout != null) {
for (int i = 0; i < 5; i++) {
tabLayout.getTabAt(i).setIcon(tabIcons[i]);
}
}
它可能有所帮助。
TabLayout
中选项卡选择的正确答案是:
TabLayout.Tab currentTab = mTabs.getTabAt(selectedTab);
if (currentTab != null) {
View customView = currentTab.getCustomView();
if (customView != null) {
customView.setSelected(true);
}
currentTab.select();
}
其中currentTab.select()
将指标移动到选定的选项卡,当customView.setSelected()
将使自定义视图中的所有项目从选择器中选择所选的状态。
填写完毕后,请尝试选择该选项卡。
TabLayout tabLayout = setTabLayout();
if (tabLayout != null) {
for (int i = 0; i < 4; i++) {
tabLayout.getTabAt(i).setIcon(tabIcons[i]);
}
tabLayout.getTabAt(0).select();
}
这里是解决方案,将此代码粘贴到onCreate Activity中,因为使用tabs 0 index不能直接触发这是一种简单的方法
viewPager.setCurrentItem(1);
if (viewPager.getCurrentItem()==1)
{
viewPager.setCurrentItem(0);
}
在我的情况下,我只想将矢量drawable添加到选择器文件中,因为它不起作用,所以如果你想使用Vector drawable,你必须将它们作为单独的文件添加...
<item android:drawable="@drawable/stnkb_tab_recent_selected_true" android:state_selected="true" />
<item android:drawable="@drawable/stnkb_tab_recent_selected_false" />