当slidetab在片段内时使用setCurrentItem

时间:2015-10-06 06:06:32

标签: android android-fragments tabs swipe

按下按钮时,我的应用程序必须在片段之间滑动。如果我在活动中托管滑动选项卡和查看寻呼机,我会做这样的事情。

((ParentActivityName) getActivity()).setCurrentItem(2, true);

现在我有一个托管幻灯片标签的父片段。它具有以下方法将当前子Fragment设置为viewpager。

public void setCurrentItem (int item, boolean smoothScroll) {
    pager.setCurrentItem(item, smoothScroll);
}

点击"下一步"其中一个滑动选项卡片段中的按钮,我试图将该方法称为

new FragUserRegistration().setCurrentItem(1,true);

但是只是返回一个空对象引用错误。任何帮助将非常感激。

2 个答案:

答案 0 :(得分:2)

我只是通过从父片段调用viewpager到每个滑动标签片段然后关联的setCurrentItem方法来解决这个问题。

viewPager = (ViewPager)getActivity().findViewById(R.id.pager);
viewPager.setCurrentItem(int position, true);    
//four swipe-able fragments so position - -> 1-3 (total count 4)

答案 1 :(得分:0)

I am not sure where your click happens to set the current item. Maybe you'll find this useful:

Your MainFragment:

 @Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    //init view
MainViewPageAdapter mainViewPageAdapter = new MainViewPageAdapter(getChildFragmentManager());
    yourViewPager.setAdapter(mainViewPageAdapter);
    return view;
}

 private class MainViewPageAdapter extends FragmentStatePagerAdapter {

    private static final int MAX_COUNT = 2;

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

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = null;
        switch (position) {
            case 1:
                fragment = YourChildFragmentOne.getInstance();
                break;
            case 2:
                fragment = YourChildFragmentTwo.getInstance();
                break;
          }
        return fragment;
    }

    @Override
    public int getCount() {
        return MAX_COUNT;
    }
}

In your ChildFragment(s):

(or create an abstract ChildFragment, which handles the click listener and create two instances of the abstract one)

private OnChildFragmentClickListener mClickListener;

    @Override
public void onAttach(Context context) {
    super.onAttach(context);
    mClickListener = (OnChildFragmentClickListener) getParentFragment();
}

//call somewhere in your ChildFragment mClickListener.onChildFragClick(index);

public interface OnChildFragmentClickListener{
 void onChildFragClick(int index);
}

Now let your MainFragment implement OnChildFragmentClickListener and call there:

@Override
public void onChildFragClick(int index){
yourViewPager.setCurrentItem(index);
}