我在我的活动中设置了一个标签滑块,根据所选的片段调用3个独立的片段。问题是当选择第一个选项卡时,会显示“Science” - 它是在第一个片段的onCreateView()方法上设置的。但是,在没有单击其他选项卡的情况下,将显示“技术”和“运动”。
据我所知,我最后两个实现它的方式只应在选择相应的选项卡后显示。
这是我的页面适配器类
public class PagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3; //Represents the number of tabs
private String tabTitles[] = new String[]{"Technology", "Science", "Sports"}; //Tab values defined in an array
private Context context;
public PagerAdapter(FragmentManager fm, Context context)
{
super(fm);
this.context = context;
}
@Override
public int getCount()
{
return PAGE_COUNT;
}
//determines the fragment depending on the selected tab
@Override
public Fragment getItem(int position)
{
if(position==0)
return TechnologyFragment.newInstance(position+1);
else if(position==1)
return ScienceFragment.newInstance(position+1);
else if(position==2)
return SportsFragment.newInstance(position+1);
else
return null;
}
//displays the title for each tab
@Override
public CharSequence getPageTitle(int position)
{
// Generate title based on item position
return tabTitles[position];
}
}
这是新闻类 - 设置了视图寻呼机和标签布局
public class News extends AppCompatActivity {
//Here the viewPager is connected to the PagerAdapter class
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
//This component will be used to page between the various fragments created.
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new PagerAdapter(getSupportFragmentManager(), News.this));
//the tabLayout is given the viewPager to connect to the pager with the tabs
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
//the following was used so the tabs fill up the width of the screen being responsive for all devices and orientations
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
}
}
这些是片段类 - (其他两个是相同的,但使用Toast表示不同的消息)
public class ScienceFragment extends Fragment {
//other methods
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_science_fragment, container, false);
toShow=getAll();
GridView gridView = (GridView)view.findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(getContext(),toShow));
Toast.makeText(getContext(), "Science", Toast.LENGTH_SHORT).show();
return view;
}
}
感谢任何帮助