[英]How can I add a ViewPager to a Navigation Drawer Item in Android application?
I want to add a viewPager for main fragment in my android app. 我想在我的Android应用程序中为主片段添加一个viewPager。
This is the xml file for main fragment 这是主要片段的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>
This is the Java code for Main Fragment 这是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);
}
}
You have a DrawerLayout page. 你有一个DrawerLayout页面。 It's about your drawer contains. 这是关于你的抽屉包含。 İn the DrawerLayout XML
在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">
add this code below 在下面添加此代码
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
write this code and setup your View pager
like example 编写此代码并设置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;
}
}
}
I hope Help you 希望对你有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.