我有两个标签。默认情况下,会选择0的位置选项卡,但我想选择第一个位置的选项卡。
我试过了TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
TabLayout.Tab tab = tabLayout.getTabAt(someIndex);
tab.select();
但也没有用。我也搜索stackoverflow并应用于位置1,但我的应用程序崩溃了。
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Add Expense"));
tabLayout.addTab(tabLayout.newTab().setText("Add Ledger"));
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager2);
final TabAdapter adapter = new TabAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.getTabAt(1).select();
// }
tabLayout.addOnTabSelectedListener (new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
TabAdapter:
class TabAdapter extends FragmentStatePagerAdapter {
private int mNumOfTabs;
TabAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new AddExpenseFragment();
case 1:
return new AddLedgerFragment();
}
return null;
}
@Override
public int getCount() {
return mNumOfTabs;
}
}
答案 0 :(得分:2)
尝试viewPager.setCurrentItem(pos);
答案 1 :(得分:0)
我在我的项目中使用以下代码并且工作正常。但在此之前,您必须使用View Pager设置标签布局
tabLayout = (TabLayout)view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(1).select();