我内部有一个名为RegisterActivity的活动,正在强制包含两个片段的ViewPager。这是活动代码
public class RegisterActivity extends AppCompatActivity{
private Context context;
private Toolbar toolbar;
private TabLayout tabLayout;
public static ViewPager viewPager;
private ViewPagerAdapter adapter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
context = RegisterActivity.this;
viewPager = findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FragmentOne(), "Step 1");
adapter.addFragment(new FragmentTwo(), "Step 2");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
@Override
public int getCount() {
return fragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
}
片段一具有NEXT按钮。当按下此按钮时,我希望视图寻呼机滚动到FragmentTWo。 FragmentTwo再次具有一个BACK按钮,当希望按下BACK按钮(在FragmentTwo布局中存在)时,我希望视图寻呼机滚动到fragmentOne。
答案 0 :(得分:1)
RegisterActivity.viewpager.setCurrentItem(片段的位置);
//只需在片段中的按钮上单击此按钮,就需要具体说明片段在寻呼机适配器中的位置