本篇文章给大家分享的是有关Android中怎么利用ViewPager实现图片滑动预览效果,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
xml代码:
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.blog_0615.MainActivity"> <android.support.v4.view.ViewPager android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/vp_main_viewpager" ></android.support.v4.view.ViewPager> </android.support.constraint.ConstraintLayout>
Activity代码:
package com.example.blog_0615; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { //定义图片数组 private int images[]={R.drawable.bird,R.drawable.cat,R.drawable.chicken}; //定义一个View的数组 private List<View> views=new ArrayList<>(); private ViewPager vp_main_viewpager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); vp_main_viewpager = (ViewPager) findViewById(R.id.vp_main_viewpager); //将images数组中的图片放入ImageView for (int i = 0; i < images.length; i++) { ImageView imageView=new ImageView(this); imageView.setImageResource(images[i]); views.add(imageView); } //为ViewPager设置适配器 vp_main_viewpager.setAdapter(new MyAdapter()); } class MyAdapter extends PagerAdapter { @Override public int getCount() { return views.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view==object; } @Override public Object instantiateItem(ViewGroup container, int position) { View v=views.get(position); container.addView(v); return v; } @Override public void destroyItem(ViewGroup container, int position, Object object) { View v=views.get(position); //前一张图片划过后删除该View container.removeView(v); } } }
以上就是Android中怎么利用ViewPager实现图片滑动预览效果,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注编程网行业资讯频道。