18

我正在使用来自 Android 的新支持 TabLayout。问题是我想在选择选项卡时使用选择器来更改图标。

我一直在研究源代码,在我看来它永远不会改变视图的状态(因此我不能使用选择器)。

有谁知道一些解决方法?

谢谢!

4

5 回答 5

59

假设您的 my_selector.xml 是,

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/icon_on" android:state_selected="true"/>
    <item android:drawable="@drawable/icon_off"/> <!-- default -->
</selector>

然后你可以直接调用 setIcon,

tab.setIcon(R.drawable.my_selector);

使用“com.android.support:design:22.2.0”验证。

于 2015-08-12T04:05:57.197 回答
1

我发现当我第一次为 TabLayout 中的每个选项卡设置自定义视图时,我需要将第一个(索引 0)设置为选中状态。

    TabLayout toolbarTabLayout = (TabLayout) findViewById(R.id.tabs);
    toolbarTabLayout.setupWithViewPager(mViewPager);
    toolbarTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    toolbarTabLayout.setTabMode(TabLayout.MODE_FIXED);
    toolbarTabLayout.setTabTextColors(R.color.colorPrimary, R.color.white);
    // Iterate over all tabs and set the custom view
    for (int i = 0; i < toolbarTabLayout.getTabCount(); i++) {
        TabLayout.Tab tab = toolbarTabLayout.getTabAt(i);
        View v=mSectionsPagerAdapter.getTabView(i);
        // no tabs are actually selected at start, this will make sure the
        // selector for the colors comes in right when initialized
        if (i==0)
            v.setSelected(true);
        tab.setCustomView(v);
    }

这似乎会在应用自定义视图时强制选择第一个选项卡。这真的感觉像是一个黑客,希望其他人能找出真正的问题并提出更好的解决方案。

于 2015-11-11T02:24:20.977 回答
0

可以使用setCustomView(View view)方法将 customView 设置为选项卡。因此,您可以创建一个 textview 并为其设置选择器并将此视图设置为选项卡。

希望对你有帮助!

于 2015-06-24T06:42:33.743 回答
0

如果你做的一切都是正确的(我相信这一点),那么你到达的点和我一样。也许这是新的 android appcompat 库中的一个小错误。

我找到了一种解决方法(在葡萄牙语中称为 Gambiarra)来解决这个问题。您需要从 Tab 类中调用方法 select() ,如下所示:

mTabLayout.getTabAt(x).select();

但它非常重要:x 变量必须不同于当前选定的选项卡索引。

于 2015-07-28T19:51:39.190 回答
0

这对我有用:

假设您将选择器设置在可绘制 res 文件夹中(如上图所示的Xingang Huang)。在您的 MainActivity(您设置 TabLayout 的位置)中包含图标选择器数组,然后像这样循环遍历它:

for (int i = 0; i < yourTabLayout.getTabCount(); i++) {
        ImageView imageView = new ImageView(this); //your context, in this case MainActivity.class
        imageView.setImageResource(arr_tabIcons[i]); //tabIcons is the array of icons
        if (i==0) {
            imageView.setSelected(true); 
        }
        yourTabLayout.getTabAt(i).setCustomView(imageView);

    }

tab.setIcon(R.drawable.icon)

也可以,但在我的情况下,图标看起来非常小,所以我不得不使用 ImageView 的解决方案来填充选项卡视图。

快乐编码;)

于 2017-05-28T05:54:42.630 回答