Android选项卡布局setIcon方法仅在OnTabSelectedListener内部工作



我正试图在活动的onCreate方法中使用此代码为选项卡布局的选项卡设置图标

tabLayout.getTabAt(0).setIcon(R.drawable.icon0);
tabLayout.getTabAt(1).setIcon(R.drawable.icon1);
tabLayout.getTabAt(2).setIcon(R.drawable.icon2);

因为它应该工作得很好,因为类似的TabLayout.Tab方法,如

tabLayout.getTabAt(0).getOrCreateBadge().setNumber(number);

在完全相同的范围内做,它没有。

奇怪的是,如果我把它放在选项卡布局的OnTabSelectedListener中,同样的代码也能工作

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
tabLayout.getTabAt(0).setIcon(R.drawable.icon0);
tabLayout.getTabAt(1).setIcon(R.drawable.icon1);
tabLayout.getTabAt(2).setIcon(R.drawable.icon2);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});

据我所知,这背后没有任何逻辑。这是bug还是我遗漏了什么?如何在不使用侦听器的情况下使用这些方法?

我使用以下版本的库:

implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.google.android.material:material:1.2.0-alpha01'

调用setupWithViewPager方法后,尝试将图标设置为选项卡。

tabLayout.setupWithViewPager(viewPager);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setIcon(R.drawable.your_icon);
}

相关内容

  • 没有找到相关文章

最新更新