我有android应用程序。 申请minSDK:15
我有NavigationDrawer。 单击第一个导航抽屉菜单项时,我的新片段显示为MainFragment。 一切都很好,就像在android教程中一样。
现在在这个片段中我需要实现简单的ViewPager。 ViewPager将页面碎片。
这是代码:
public class MainFragent extends Fragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.main_fragment_layout, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<Books> books;
BooksPageAdapter contentPageAdapter = new BooksPageAdapter(getFragmentManager(), books);
ViewPager pager = (ViewPager) getActivity().findViewById(R.id.viewPager);
pager.setAdapter(contentPageAdapter);
}
private class BooksPageAdapter extends FragmentStatePagerAdapter {
private ArrayList<Books> books;
public BooksPageAdapter(FragmentManager fm, private ArrayList<Books> books) {
super(fm);
this.books = books;
}
@Override
public Fragment getItem(int pos) {
return BooksFragment.newInstance(books);
}
@Override
public int getCount() {
return 5;
}
} }
和BooksFragment:
public class BooksFragment extends Fragment {
private ArrayList<Books> books;
static ContentFragment newInstance(final ArrayList<Books> books) {
BooksFragment booksFragment = new BooksFragment();
Bundle args = new Bundle();
args.putSerializable("books", books);
contentFragment.setArguments(args);
return booksFragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
books = (ArrayList<Books>) getArguments().getSerializable(“books”);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_books, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onResume() {
super.onResume();
updateUI(books);
}
public void updateUI(ArrayList<Books> books) {
ListView listView = (ListView)getActivity().findViewById(R.id.list_view);
listView.setAdapter(new MyArrayAdapter(getActivity(), books));
}
private class MyArrayAdapter extends ArrayAdapter<Books> {
public MyArrayAdapter(final Context context, final List<Books> list) {
super(context, R.layout.books_menu_item, R.id.title, list);
}
@Override
public View getView(final int position,
final View convertView,
final ViewGroup parent) {
final View row = super.getView(position, convertView, parent);
Book book = getItem(position);
textView.setText(book.getTitle());
return row;
}
}
}
FirstPage看起来很棒,就像它应该的那样。我看到书名列表。 但在第二页上,列表视图为空。除了ListView之外,第二页上的所有其他视图(如TextView ..)都很好。 我做错了什么?
P.S FragmentStatePageAdapter来自support13。片段来自android包,而不是来自support4