目录:android.support.v4.view.ViewPager
xml布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="@+id/vp_viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
代码使用:
public class MainActivity extends AppCompatActivity {
private ViewPager vp_viewPager;
private List<View> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
vp_viewPager = (ViewPager) findViewById(R.id.vp_viewPager);
//子item是Fragment使用该适配器(推荐使用)
vp_viewPager.setAdapter(new FmVpAdapter(getSupportFragmentManager()));
//子item是view使用该适配器
// list = new ArrayList<>();
// for (int i = 0; i < 5; i++) {
// TextView tv = new TextView(this);
// tv.setText("我是界面"+i);
// list.add(tv);
// }
// vp_viewPager.setAdapter(new VpAdapter(list));
}
//子item是Fragment使用该适配器
private class FmVpAdapter extends FragmentPagerAdapter {
public FmVpAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return new VpFragment();//每个碎片都会被标识,使用过的碎片会被复用
}
@Override
public int getCount() {
return 3;//更换自己数据源数量
}
}
//子item是view使用该适配器
private class VpAdapter extends PagerAdapter{
List<View> list;
public VpAdapter(List<View> list) {
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0==arg1;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(list.get(position));
return list.get(position);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
//.destroyItem(container, position, object);
container.removeView(list.get(position));
}
}
}
碎片:
xml布局:fragment_vp_page.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv_page"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="碎片页面" />
</LinearLayout>
碎片
public class VpFragment extends Fragment {
private View view;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_vp_page, null);
init();
return view;
}
private void init() {
TextView tv_page = (TextView) view.findViewById(R.id.tv_page);
}
}
注意:
1、Fragment导入的都是V4包的类