在FragmentPagerAdapter的getItem(int position)方法中,此行PlaceholderFragment.newInstance(position + 1)决定它返回哪个片段。 只有一种类型的片段,并返回的片段具有相同的布局,但在PlaceholderFragment你可以改变它根据位置的布局,例如:
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
private int mPosition;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPosition = getArguments().getInt(ARG_SECTION_NUMBER);
}
private View mRootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
switch (mPosition) {
case 0:
mRootView = inflater.inflate(R.layout.fragment_layout_0, container, false);
break;
case 1:
mRootView = inflater.inflate(R.layout.fragment_layout_1, container, false);
break;
case 2:
mRootView = inflater.inflate(R.layout.fragment_layout_2, container, false);
break;
}
TextView textView = (TextView) mRootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return mRootView;
}
}
请记住,所有的Java代码都必须在类中。 –
对不起,你是对的。 –
此外,这是最适当的做一个'PagerAdapter'和多个'Fragment'子类,每个布局一个。 –