在Android studio中使用viewpager创建出图片轮播效果

1.布局:

xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    

            android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="200dp" />

    

            android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/viewpager"
        android:background="#33000000"
        android:orientation="vertical" >

                    android:id="@+id/image_desc"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@string/app_name"
            android:textColor="@android:color/white"
            android:textSize="16sp" />

                    android:id="@+id/point_group"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginBottom="5dp"
            android:orientation="horizontal" >
        
    


2.形状属性定义:

xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >

            android:height="5dp"
        android:width="5dp" />

    android:color="#aaFFFFFF" />


xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >

            android:height="5dp"
        android:width="5dp" />

    android:color="#55000000" />


xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android">

    android:drawable="@drawable/point_nomal" android:state_enabled="false"/>
    android:drawable="@drawable/point_focured" android:state_enabled="true"/>


注:要是觉得麻烦,这个形状定义也可以直接引用andriod自带的,用imageview实现,效果一样的。

2.代码:

package com.example.viewpagerpractice2;

import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;

import com.nineoldandroids.view.ViewHelper;

/*
 * 自定义viewpager实现动画切换效果:
 * 
 * 1、拿到当前切换的两个view
 * 
 * 2、一个动画的梯度值
 */
public class MyViewPager extends ViewPager {


   private View mLeft;
   private View mRight;

   private float mTrans;
   private float mScale;

   private static final float MIN_SCALE = 0.6f;
   private Map, View> mChildren = new HashMap<>();

   /*
    * 两个构造方法
    */
   public MyViewPager(Context context, AttributeSet attrs) {
      super(context, attrs);
   }

   public MyViewPager(Context context) {
      super(context);
   }



   /**
    * 重写de方法
    */
   @Override
   protected void onPageScrolled(int position, float offset, int offsetPixels) {


      mLeft = mChildren.get(position);
      mRight = mChildren.get(position + 1);

      animStack(mLeft, mRight, offset, offsetPixels);// 创建动画效果

      super.onPageScrolled(position, offset, offsetPixels);
   }

   private void animStack(View left, View right, float offset, int offsetPixels) {
      if (right != null) {

         // 0-1页,offset:0`1
         mScale = (1 - MIN_SCALE) * offset + MIN_SCALE;

         mTrans = -getWidth() - getPageMargin() + offsetPixels;

         ViewHelper.setScaleX(right, mScale);
         ViewHelper.setScaleY(right, mScale);

         ViewHelper.setTranslationX(right, mTrans);
      }
      if (left != null) {
         left.bringToFront();
      }
   }
}

package com.example.viewpagerpractice2;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

   private ViewPager viewPager;

   private LinearLayout pointGroup;

   private TextView iamgeDesc;

   // 图片资源ID
   private final int[] imageIds = { R.drawable.a, R.drawable.b, R.drawable.c,
         R.drawable.d, R.drawable.e };

   // 图片标题集合
   private final String[] imageDescriptions = { "巩俐不低俗",
         "扑树又回来啦!", "揭秘北京电影如何升级", "乐视网大派送", "热血屌丝的反杀" };

   private ArrayList imageList;

   /**
    * 上一个页面的位置
    */
   protected int lastPosition;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      viewPager = (ViewPager) findViewById(R.id.viewpager);
      pointGroup = (LinearLayout) findViewById(R.id.point_group);
      iamgeDesc = (TextView) findViewById(R.id.image_desc);
      iamgeDesc.setText(imageDescriptions[0]);

      imageList = new ArrayList<>();
      for (int i = 0; i < imageIds.length; i++) {

         // 初始化图片资源
         ImageView image = new ImageView(this);
         image.setBackgroundResource(imageIds[i]);
         imageList.add(image);

         // 添加指示点
         ImageView point = new ImageView(this);
         LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
               LinearLayout.LayoutParams.WRAP_CONTENT,
               LinearLayout.LayoutParams.WRAP_CONTENT);

         params.rightMargin = 20;
         point.setLayoutParams(params);

         point.setBackgroundResource(R.drawable.point_bg);
         if (i == 0) {
            point.setEnabled(true);
         } else {
            point.setEnabled(false);
         }
         pointGroup.addView(point);
      }

      viewPager.setAdapter(new MyPagerAdapter());


      viewPager.setOnPageChangeListener(new OnPageChangeListener() {

         @Override
         /**
          * 页面切换后调用 
          * position  新的页面位置
          */
         public void onPageSelected(int position) {

            position = position % imageList.size();

            // 设置文字描述内容
            iamgeDesc.setText(imageDescriptions[position]);

            // 改变指示点的状态
            // 把当前点enbale true
            pointGroup.getChildAt(position).setEnabled(true);
            // 把上一个点设为false
            pointGroup.getChildAt(lastPosition).setEnabled(false);
            lastPosition = position;

         }

         @Override
         /**
          * 页面正在滑动的时候,回调
          */
         public void onPageScrolled(int position, float positionOffset,
                              int positionOffsetPixels) {
         }

         @Override
         /**
          * 当页面状态发生变化的时候,回调
          */
         public void onPageScrollStateChanged(int state) {

         }
      });

      /*
       * 自动循环: 1、定时器:Timer 2、开子线程 while true 循环 3ColckManager 4、 用handler
       * 发送延时信息,实现循环
       */
      isRunning = true;
      // 设置图片的自动滑动
      handler.sendEmptyMessageDelayed(0, 3000);
   }

   /**
    * 判断是否自动滚动
    */
   private boolean isRunning = false;

   private Handler handler = new Handler() {
      public void handleMessage(android.os.Message msg) {

         // viewPager 滑动到下一页
         viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
         if (isRunning) {
            handler.sendEmptyMessageDelayed(0, 3000);
         }
      };
   };

   protected void onDestroy() {
        super.onDestroy();
      isRunning = false;
   };

   private class MyPagerAdapter extends PagerAdapter {

      @Override
      /**
       * 获得页面的总数
       */
      public int getCount() {
         return Integer.MAX_VALUE; // 使得图片可以循环
      }

      @Override
      /**
       * 获得相应位置上的view
       * container  view的容器,其实就是viewpager自身
       * position    相应的位置
       */
      public Object instantiateItem(ViewGroup container, int position) {



         //  container 添加一个view
         container.addView(imageList.get(position % imageList.size()));
         // 返回一个和该view相对的object
         return imageList.get(position % imageList.size());
      }

      @Override
      /**
       * 判断 viewobject的对应关系 
       */
      public boolean isViewFromObject(View view, Object object) {
         if (view == object) {
            return true;
         } else {
            return false;
         }
      }

      @Override
      /**
       * 销毁对应位置上的object
       */
      public void destroyItem(ViewGroup container, int position, Object object) {

         container.removeView((View) object);

      }
   }

}

你可能感兴趣的:(Android)