使用按钮更改选项卡视图

时间:2017-07-06 17:42:36

标签: java android android-fragments button tabs

编码的新手。我按照教程创建了标签和片段。我的应用程序现在在工具栏上有3个选项卡,单击它们时会更改为各自的布局。我现在想添加一个按钮,将我带到那些布局而不是使用工具栏,所以我可以将它移动并放置在我想要的位置。

这就是我在MainActivity中的含义

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());

     //Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    setupViewPager(mViewPager);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
}

private void setupViewPager(ViewPager viewPager) {
    SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
    adapter.addFragment(new Main2Activity(), "TAB1");
    adapter.addFragment(new Main3Activity(), "TAB2");
    adapter.addFragment(new Main4Activity(), "TAB3");
    viewPager.setAdapter(adapter);
}

然后我为按钮添加了此代码。在我的XML中,我将按钮放在容器ID上方,以便我始终可以看到它。理想情况下,我有3个按钮,每个按钮都放入容器ID Main2Activity,Main3Activity和Main4Activity。这里只有一个按钮,因为我试图找出如何改变视图。

public void onClickBtn1(View v){
    FragmentManager fm = getSupportFragmentManager();
    android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();

    ft.replace(R.id.container, new Main2Activity());
    ft.commit();
}

如果它有帮助,这也是我的SectionsPageAdapter页面。

public class SectionsPageAdapter extends FragmentPagerAdapter {

private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();

public void addFragment(Fragment fragment, String title) {
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);
}

public SectionsPageAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public CharSequence getPageTitle(int position) {
    return mFragmentTitleList.get(position);
}

@Override
public Fragment getItem(int position) {
    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList.size();
}
}

提前致谢!

1 个答案:

答案 0 :(得分:1)

点击后点击ViewPager#setCurrentItem转到viewpager适配器列表/数组中项目的索引:

public void onClickBtn1(View v){
    int gotoIndex = 0;
    mViewPager.setCurrentItem(gotoIndex, /*smoothscrolling*/ true);
}