Android使用ViewPager实现图片滑动预览效果
时间:2021-12-11 09:12:29|栏目:Android代码|点击: 次
本文为大家分享了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图片滑动预览效果啦。
栏 目:Android代码
下一篇:Android Studio屏幕方向以及UI界面状态的保存代码详解
本文标题:Android使用ViewPager实现图片滑动预览效果
本文地址:http://www.codeinn.net/misctech/186523.html