在我的 android 应用程序中,我设置了这样的选项卡布局:
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("TAB 1"));
tabLayout.addTab(tabLayout.newTab().setText("TAB 2"));
tabLayout.addTab(tabLayout.newTab().setText("TAB 3"));
我想禁用选项卡 2 和选项卡 3。 我尝试了这个并且它有效:
tabLayout.getChildAt(1).setEnabled(false);
tabLayout.getChildAt(2).setEnabled(false);
但我也想设置 toast 反馈,如果有人点击禁用选项卡,例如“此选项卡未解锁”
为此,我尝试为选项卡 2 和 3 设置一个 onclicklistener。 但是如果我之前使用代码禁用选项卡,则此监听器不起作用。
有人知道我该如何解决这个问题吗?
更新
@Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() == 1) {
viewPager.setCurrentItem(0);
TabLayout.Tab tab1 = tabLayout.getTabAt(0);
tab1.select();
} else {
viewPager.setCurrentItem(tab.getPosition());
}
}
最佳答案
我的 TabLayout 如下所示
<android.support.design.widget.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TabItem
android:id="@+id/tab1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab1" />
<android.support.design.widget.TabItem
android:id="@+id/tab2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab2" />
<android.support.design.widget.TabItem
android:id="@+id/tab3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="tab3" />
</android.support.design.widget.TabLayout>
您必须将要禁用的选项卡转换为 View 对象。像这样
View tab = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(desiredPosition);
然后您可以更改可点击性并设置 alpha,以便在视觉上和功能上启用或禁用您想要的选项卡。这样
ViewGroup tabItem = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(desiredPosition);
if (isChecked) {
tabItem.setClickable(false);
tabItem.setAlpha( 0.3F);
}else {
tabItem.setClickable(true);
tabItem.setAlpha( 1F);
}
关于android 禁用 3 个选项卡中的 2 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34677699/