当我按 tab 3 时,它会显示 tab 0、tab1、tab2、tab3 的消息。但是,它显示选项卡 3 的正确内容。怎么才能只执行tab 3的内容呢?为什么它会执行其他页面?
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainscreen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(new SectionsPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount()));
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public SectionsPagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
} @Override
public Fragment getItem(int position) {
position = mViewPager.getCurrentItem();
System.out.println("This is the currnet position : " + position);
if (position == 0) {
Tab0Index tab0 = new Tab0Index();
Toast.makeText(getApplicationContext(), "tab1 active " + position, Toast.LENGTH_SHORT).show();
return tab0;
} else if (position == 1) {
Tab2Top10 tab2 = new Tab2Top10();
Toast.makeText(getApplicationContext(), "tab2 active " + position, Toast.LENGTH_SHORT).show();
return tab2;
} else if (position == 2) {
Tab3UserRanking tab3 = new Tab3UserRanking();
Toast.makeText(getApplicationContext(), "tab3 active " + position, Toast.LENGTH_SHORT).show();
return tab3;
} else if (position == 3) {
Tab4Profile tab4 = new Tab4Profile();
Toast.makeText(getApplicationContext(), "tab4 active " + position, Toast.LENGTH_SHORT).show();
return tab4;
} else if (position == 4) {
Tab5Setting tab5 = new Tab5Setting();
Toast.makeText(getApplicationContext(), "tab5 active " + position, Toast.LENGTH_SHORT).show();
return tab5;
}else{
return null;
}
@Override
public int getCount() {
// Show 5 total pages.
return mNumOfTabs;
} }}
不要在 SectionsPagerAdapter
中使用 Toast.makeText(getApplicationContext(), "tab1 active "+position, Toast.LENGTH_SHORT).show();
。当您选择页面时, View 页面已经加载上一页和下一页。因此将 toast 更改为每个 fragment (Pages)的 onResume 。例如。对于 Tab 1 fragment 的 onResume(),请使用以下代码
@Override
public void onResume() {
super.onResume();
if (getUserVisibleHint()) {
Toast.makeText(getApplicationContext(), "tab1 active " + position, Toast.LENGTH_SHORT).show();
}
}
我是一名优秀的程序员,十分优秀!