如何简单地扩展FragmentPagerAdapter?

时间:2019-07-19 23:08:16

标签: java android fragmentpageradapter

我使用ViewPager + TabLayout + Fragment来实现幻灯片片段,但是看起来很多余。我创建了四个片段,但是实际上,我不需要在每个片段中编写很多代码。大多数工作在.xml文件中完成。如何简单实现?

这是片段文件。其他三个片段与此文件相似。

public class CalibrateFragment extends Fragment {
private OnFragmentInteractionListener mListener;

public CalibrateFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.calibrate_frag, container, false);
}


@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

}

这是PagerAdapter文件:

public class PagerAdapter extends FragmentStatePagerAdapter {
int NumberOfMode;

public PagerAdapter(FragmentManager fm, int NumberOfMode) {
    super(fm);
    this.NumberOfMode = NumberOfMode;
}

@Override
public Fragment getItem(int position) {
    switch(position)
    {
        case 0:
            OverviewFragment overviewFragment = new OverviewFragment();
            return overviewFragment;
        case 1:
            CalibrateFragment calibrateFragment = new CalibrateFragment();
            return calibrateFragment;
        case 2:
            PathFragment pathFragment = new PathFragment();
            return pathFragment;

        case 3:
            PointFragment pointFragment = new PointFragment();
            return pointFragment;
        default:
            return null;
    }
}


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

}

这是MainActivity,它需要实现很多...。

public class MainActivity extends AppCompatActivity implements OverviewFragment.OnFragmentInteractionListener, CalibrateFragment.OnFragmentInteractionListener, PathFragment.OnFragmentInteractionListener, PointFragment.OnFragmentInteractionListener {}

0 个答案:

没有答案