需求
先简单的说下需求,viewpager中有两个fragment,分别是fragment1,fragment2,在fragment1中有一个按钮,点击这个按钮可以跳转到fragment2
原理
给fragment1传递MainActivity中的viewpager对象,然后调用其viewpager对象的setCurrentItem()方法即可。
代码
MainActivity.java
public class MainActivity extends FragmentActivity {
private VerticalViewPager mViewpager;
private List<Fragment> mFragmentList = new ArrayList<>();
private MyFragment1 mFragment1;
private MyFragment2 mFragment2;
private FragmentManager mManager;
private MyAdapter mAdapter;
private FragmentSkipInterface mFragmentSkipInterface;
public void setFragmentSkipInterface(FragmentSkipInterface fragmentSkipInterface) {
mFragmentSkipInterface = fragmentSkipInterface;
}
/** Fragment跳转 */
public void skipToFragment(){
if(mFragmentSkipInterface != null){
mFragmentSkipInterface.gotoFragment(mViewpager);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
mViewpager = (VerticalViewPager) findViewById(viewpager);
mFragment1 = new MyFragment1();
mFragment2 = new MyFragment2();
mFragmentList.add(mFragment1);
mFragmentList.add(mFragment2);
mManager = getSupportFragmentManager();
mAdapter = new MyAdapter(mManager,mFragmentList);
mViewpager.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
public interface FragmentSkipInterface {
/** ViewPager中子Fragment之间跳转的实现方法 */
void gotoFragment(VerticalViewPager viewPager);
}
}
fragement1.java
public class MyFragment1 extends Fragment implements View.OnClickListener {
private Button mBtn;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1_layout,container,false);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mBtn = view.findViewById(R.id.btnClick);
mBtn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
final MainActivity mainActivity = (MainActivity) getActivity();
mainActivity.setFragmentSkipInterface(new MainActivity.FragmentSkipInterface() {
@Override
public void gotoFragment(VerticalViewPager viewPager) {
/** 跳转到第二个页面的逻辑 */
viewPager.setCurrentItem(1);
}
});
/** 进行跳转 */
mainActivity.skipToFragment();
}
}
网友评论