Android TabLayout 在启动时选择第一个 Tab [英] Android TabLayout select first Tab on Startup
问题描述
我正在使用 Android 设计库中的 TabLayout.我有多个选项卡,每个选项卡在被选中时都有一个操作.所以我有一个属性 startSelection,它执行
I'm using TabLayout from Android Design Library. I have multiple tabs and each Tab has an action when it is selected. So I have an attribute startSelection, which performs
tabLayout.getTabAt(startSelection).select();
这将选择选项卡并为此选项卡执行操作.它适用于除第一个选项卡之外的每个选项卡,该选项卡在启动时自动选择,无需 (!) 执行操作.有没有人对此有解决方案?
This selects the tab and performs the action for this tab. It works fine for each Tab except the first one, which is automatically selected on Startup without (!) performing the action. Does anyone have a solution for this?
我不想使用 onTabReselected 方法,因为这会导致 TabLayout 的另一种行为.同样选择第二个标签然后选择第一个标签也不是一个好的解决方案.
I don't want to use the onTabReselected method, because this causes another behaviour of the TabLayout. Also selecting the second tab and selecting the first tab afterwards is no good solution.
最好的问候
推荐答案
我明白了.解决方案很简单,使用(一次)onTabReselected 并覆盖那里的侦听器.
I got it. The solution is simple, use (once) onTabReselected and overwrite listener there.
tabLayout.setOnTabSelectedListener(new OnTabSelectedListener() {
@Override
public void onTabSelected(Tab tab) {
selectTab(tab);
}
private void selectTab(Tab tab) {
// do something
}
@Override
public void onTabReselected(Tab tab) {
if (tab.getPosition() == 0) {
selectTab(tab);
tabLayout.setOnTabSelectedListener(new OnTabSelectedListener() {
@Override
public void onTabSelected(Tab tab) {
selectTab(tab);
}
@Override
public void onTabReselected(Tab arg0) {
}
@Override
public void onTabUnselected(Tab arg0) {
}
});
}
}
@Override
public void onTabUnselected(Tab tab) {
}
});
这篇关于Android TabLayout 在启动时选择第一个 Tab的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!