前言
Android控件ViewPage学习笔记
有点像轮播图效果
创建多个布局
/app/src/main/res/layout/layout1.xml
1 2 3 4 5 6 7
| <?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:background="#FF0000">
</LinearLayout>
|
/app/src/main/res/layout/layout2.xml
1 2 3 4 5 6 7
| <?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:background="#00FF00">
</LinearLayout>
|
/app/src/main/res/layout/layout3.xml
1 2 3 4 5 6 7
| <?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:background="#0000FF">
</LinearLayout>
|
创建构造器
/app/src/main/java/…/MyAdapter.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| public class MyAdapter extends PagerAdapter {
private List<View> viewList;
public MyAdapter(List<View> viewList) { this.viewList = viewList; }
@Override public int getCount() { return viewList.size(); }
@NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { container.addView(this.viewList.get(position), 0); return this.viewList.get(position); }
@Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view == object; }
@Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { container.removeView(this.viewList.get(position)); } }public class MyAdapter extends PagerAdapter {
private List<View> viewList;
public MyAdapter(List<View> viewList) { this.viewList = viewList; }
@Override public int getCount() { return viewList.size(); }
@NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { container.addView(this.viewList.get(position), 0); return this.viewList.get(position); }
@Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view == object; }
@Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { container.removeView(this.viewList.get(position)); } }
|
通过构造器将布局渲染页面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| View view1 = getLayoutInflater().inflate(R.layout.layout1, null); View view2 = getLayoutInflater().inflate(R.layout.layout2, null); View view3 = getLayoutInflater().inflate(R.layout.layout3, null);
List<View> viewList = new ArrayList<>(); viewList.add(view1); viewList.add(view2); viewList.add(view3);
MyAdapter myAdapter = new MyAdapter(viewList);
ViewPager viewPager = findViewById(R.id.vp); viewPager.setAdapter(myAdapter);
|
完成
参考文献
哔哩哔哩——Android架构解析