gpt4 book ai didi

java - 如何在 Android studio 中只执行一个选项卡的内容?

转载 作者:太空宇宙 更新时间:2023-11-04 10:36:54 25 4
gpt4 key购买 nike

当我按 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();
}
}

关于java - 如何在 Android studio 中只执行一个选项卡的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49359471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com