第四章、android入門
阿新 • • 發佈:2021-11-18
目錄
安卓入門
七、ViewPager
1、ViewPager
- layout1.xml、layout2.xml、layout3.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:background="#ffff0000" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="layout1" android:textSize="30sp" /> </LinearLayout>
- activity_main.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"> <androidx.viewpager.widget.ViewPager android:id="@+id/vp" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
- MyAdapter
public class MyAdapter extends PagerAdapter { private List<View> mListView; public MyAdapter(List<View> mListView) { this.mListView = mListView; } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { container.addView(mListView.get(position), 0); return mListView.get(position); } @Override public int getCount() { return mListView.size(); } @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(mListView.get(position)); } }
- MainActivity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater lf = getLayoutInflater().from(this);
View view1 = lf.inflate(R.layout.layout1, null);
View view2 = lf.inflate(R.layout.layout2, null);
View view3 = lf.inflate(R.layout.layout3, null);
ArrayList<View> viewList = new ArrayList<>();
viewList.add(view1);
viewList.add(view2);
viewList.add(view3);
ViewPager viewPager = findViewById(R.id.vp);
MyAdapter myAdapter = new MyAdapter(viewList);
viewPager.setAdapter(myAdapter);
}
}