ViewPager的使用
Posted sj-anhui
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ViewPager的使用相关的知识,希望对你有一定的参考价值。
代码:
1 public class MainActivity extends AppCompatActivity { 2 private ViewPager viewPager; 3 private int[] imgs = {R.drawable.img_01,R.drawable.img_02,R.drawable.img_03}; 4 5 @Override 6 protected void onCreate(Bundle savedInstanceState) { 7 super.onCreate(savedInstanceState); 8 setContentView(R.layout.activity_main); 9 viewPager = findViewById(R.id.vp_pager); 10 initData(); 11 } 12 13 private void initData() { 14 List<View> viewList = new ArrayList<>(); 15 for (int i = 0; i < imgs.length; i++) { 16 View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main_item, 17 null,false); 18 ImageView imageView = view.findViewById(R.id.iv_item_img); 19 imageView.setImageResource(imgs[i]); 20 viewList.add(view); 21 } 22 viewPager.setAdapter(new ImageAdapter(viewList)); 23 } 24 25 public class ImageAdapter extends PagerAdapter{ 26 private List<View> viewList; 27 public ImageAdapter(List<View> viewList) { 28 this.viewList = viewList; 29 } 30 31 @Override 32 public int getCount() { 33 return imgs.length; 34 } 35 36 @Override 37 public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { 38 return view == object; 39 } 40 41 @NonNull 42 @Override 43 public Object instantiateItem(@NonNull ViewGroup container, int position) { 44 container.addView(viewList.get(position)); 45 return viewList.get(position); 46 } 47 48 @Override 49 public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { 50 container.removeView(viewList.get(position)); 51 } 52 } 53 }
布局:
1 <android.support.v4.view.ViewPager 2 android:id="@+id/vp_pager" 3 android:layout_width="match_parent" 4 android:layout_height="300dp" 5 android:layout_centerInParent="true" />
以上是关于ViewPager的使用的主要内容,如果未能解决你的问题,请参考以下文章
当 ViewPager 中的片段出现和消失时如何执行一些代码