TabLayout selected 启动时未选择选项卡图标 [英] TabLayout selected Tab icon is not selected on start up

查看:20
本文介绍了TabLayout selected 启动时未选择选项卡图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用中使用 TabLayout 进行选项卡式导航.我有一个非常奇怪的问题,我使用此代码创建了 4 个选项卡:

I'm using a TabLayout for Tabbed navigation in my app. I have a really weird issue with it, I have created 4 tabs using this code:

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 具有选中和未选中状态.所有图标选择器的配置如下:

Each of the items in tabIcon is a selector with selected and non-selected states. All icon selectors are configured as follows:

<?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)时,不使用选定状态图标.相反,它使用非选中状态.

The problem is that when the application starts the first selected tab (index 0) does not use the selected state icon. Instead it uses the non-selected state.

为了更便于说明,这里是问题的屏幕截图,在第一次启动时,我的标签看起来像这样:

To be more explanatory here is a screenshot of the issue, on first start my tab looks like this:

什么时候应该是这样的:

when instead it should be like this:

更改页面后,所有图标都恢复完整功能,并且正确选择了所选状态.

After I change a page all the icons come back to full functionality, and the selected states are selected properly.

我尝试使用 TabLayout.Tab select() 方法,但结果相同,使用的图标是未选中的图标.

I tried to use the TabLayout.Tab select() method but the result is the same the icon that is used is the not selected icon.

有人知道我可以做些什么来解决它吗?

Does someone know what I can do to fix it?

推荐答案

TabLayout中选项卡选择的正确答案是:

The correct answer for tab selection in TabLayout would be:

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() 将使自定义视图中的所有项目设置为选定的选择器中的状态看起来被选中.

where currentTab.select() will move the indicator to the selected tab, when customView.setSelected() will make all the items in the custom view set their selected states from the selectors look selected.

这篇关于TabLayout selected 启动时未选择选项卡图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆