首页 > 其他 > 详细

ViewPager的使用

时间:2018-12-17 22:30:10      阅读:161      评论:0      收藏:0      [点我收藏+]

代码:

 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的使用

原文:https://www.cnblogs.com/sj-anhui/p/10134281.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!