如何从片段中获取位于片段中的ViewPager?

时间:2018-06-21 14:00:00

标签: android xml android-fragments android-viewpager

我不确定如何获取位于Fragment中的ViewPager的引用。我知道,如果VP处于活动中,我可以调用:vp = getActivity()。findViewById(R.id.vpObserve);

如果ViewPager位于片段中,该怎么办?

供参考:这是包含VP的片段

public class AddReflectionFrag extends Fragment {
    private ViewPager mPager;
    private SlideTabPagerAdapter mPad;
    private TabLayout tl;
    @Nullable
    @Override

    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.vp_reflection, container, false);

        mPager = (ViewPager) root.findViewById(R.id.vpReflect);
        tl = (TabLayout) root.findViewById(R.id.tabs);
        setUpAdapters();

        return root;
    }

    private void setUpAdapters(){
        mPad = new SlideTabPagerAdapter(getChildFragmentManager());
        mPad.addFragment(new ReflectionFormFrag());
        mPad.addFragment(new EvidenceFragment());
        mPager.setAdapter(mPad);

        tl.setupWithViewPager(mPager);
        tl.getTabAt(0).setText("Reflection");
        tl.getTabAt(1).setText("Evidence");
    }
}

这是我想要获得副总裁的片段(以便我可以使用next按钮移至下一个选项卡):

public class ReflectionFormFrag extends Fragment {
    OnSubmitButtonClick submitClick;
    DataSource mDataSource;
    ViewPager vp;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View root = inflater.inflate(R.layout.frag_learner_add_reflection, container, false);

        mDataSource = new DataSource(getActivity());
        mDataSource.open();
        setUpSubmit(root);
        vp = container.findViewById(R.id.vpReflect);

        return root;
    }

    public void setUpNext(final View root){
        Button next = root.findViewById(R.id.nextButt);
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                vp.setCurrentItem(vp.getCurrentItem()+1);
            }
        });
    }
}

谢谢!

0 个答案:

没有答案