我想在我的Android应用程序中为主片段添加一个viewPager。
这是主片段
的xml文件<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
这是Main Fragment的Java代码
public class MainFragment extends ListFragment {
private static final String TAG = MainFragment.class.getSimpleName();
private StudentsDBHandler studentsDBHandler;
public MainFragment() {
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
studentsDBHandler = new StudentsDBHandler(getActivity());
View rootView = inflater.inflate(R.layout.main_fragment, container, false);
displayStudents();
return rootView;
}
private void displayStudents() {
List<Student> studentList = studentsDBHandler.getAll();
ArrayAdapter<Student> list = new ArrayAdapter<>(getActivity(), R.layout.item_student, studentList);
setListAdapter(list);
}
}
答案 0 :(得分:0)
你有一个DrawerLayout页面。这是关于你的抽屉包含。
在DrawerLayout XML
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
在下面添加此代码
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
编写此代码并设置您的View pager
示例
viewPager=(ViewPager)findViewById(R.id.viewPager);
FragmentManager fm=getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fm));
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
if(position==0)
fragment= new Home1();
if(position==1)
fragment=new Home2();
return fragment;
}
@Override
public int getCount() {
return 2;
}
}
}
我希望帮助你