码迷,mamicode.com
首页 > 移动开发 > 详细

Android自定义控件之应用程序首页轮播图

时间:2014-09-28 12:58:52      阅读:343      评论:0      收藏:0      [点我收藏+]

标签:android应用   自定义控件   viewpager   首页轮播   uri   

现在基本上大多数的Android应用程序的首页都有轮播图,就是像下图这样的(此图为转载的一篇博文中的图,拿来直接用了):

bubuko.com,布布扣

像这样的组件我相信大多数的应用程序都会使用到,本文就是自定义一个这样的组件,可以动态设置图片的张数。下面就开始本次的自定义之旅吧,首先看一下自定义控件的的布局文件:

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

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
<span style="white-space:pre">	</span><!--此LinearLayout用来小圆点-->
    <LinearLayout
        android:id="@+id/linearlayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:gravity="center"
        android:orientation="horizontal"
        android:padding="5dp" >
    </LinearLayout>

</RelativeLayout>
布局文件看完之后,我们再来看一下自定义控件相对应的java类吧:
具体代码如下:

package com.gc.view;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.gc.image.ImageLoaderWraper;
import com.gc.testviewpagerfragment.R;



import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;



/**
 * ViewPager实现的轮播图广告自定义视图;
 *  既支持自动轮播页面也支持手势滑动切换页面,可以动态设置图片的张数
 * @author Android将军
 *
 */
@SuppressLint("HandlerLeak")
public class SlideShowView extends FrameLayout {

   
	private ImageLoaderWraper imageLoaderWraper;//UIL开源框架的使用,主要用来加载图片防止OOM

    private final static boolean isAutoPlay = true; 
    private List<String> imageUris;
    private List<ImageView> imageViewsList;
    private List<ImageView> dotViewsList;
    private LinearLayout mLinearLayout;
  
    private ViewPager mViewPager;
    private int currentItem  = 0;
    private ScheduledExecutorService scheduledExecutorService;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
    	@Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            mViewPager.setCurrentItem(currentItem);
        }
        
    };
    public SlideShowView(Context context) {
        this(context,null);
    }
    public SlideShowView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public SlideShowView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
       
        initUI(context);
        if(!(imageUris.size()<=0))
        {
        	System.out.println("XXXXXXXXXXXX");
        	 setImageUris(imageUris);
        }
        	
        if(isAutoPlay){
            startPlay();
        }
        
    }
    private void initUI(Context context){
    	  imageViewsList = new ArrayList<ImageView>();
          dotViewsList = new ArrayList<ImageView>();
          imageUris=new ArrayList<String>();
          imageLoaderWraper=ImageLoaderWraper.getInstance(context.getApplicationContext());
          LayoutInflater.from(context).inflate(R.layout.layout_slideshow, this, true);
          mLinearLayout=(LinearLayout)findViewById(R.id.linearlayout);
          mViewPager = (ViewPager) findViewById(R.id.viewPager);
          
         
    }
    public void setImageUris(List<String> imageuris)
    {
    	
    	for(int i=0;i<imageuris.size();i++)
    	{
    		imageUris.add(imageuris.get(i));
    		System.out.println("YYYYYYYYYY");
    	}
    	LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(5, 0, 0, 0);
        for(int i=0;i<imageUris.size();i++){
        	ImageView imageView=new ImageView(getContext());
        	imageView.setScaleType(ScaleType.FIT_XY);//铺满屏幕
        	System.out.println("GGGGG:"+imageUris.get(i));
        	imageLoaderWraper.displayImage(imageUris.get(i), imageView);//用开源框架加载图片,读者可以自行更改,使用setsetBackgroundResource也行
        	System.out.println("JJJJJJ");
        	imageViewsList.add(imageView);
        	System.out.println("JJJJJJ55555");
        	ImageView viewDot =  new ImageView(getContext());
        	System.out.println("JJJJJJ88888");
        	  if(i == 0){  
        		  viewDot.setBackgroundResource(R.drawable.dot_black);  
              }else{  
            	  viewDot.setBackgroundResource(R.drawable.dot_white);  
              }  
        	//viewDot.setImageResource(R.drawable.dot_white);
        	System.out.println("JJJJJJ9999");
        	viewDot.setLayoutParams(lp);
        	dotViewsList.add(viewDot);
        	mLinearLayout.addView(viewDot);
        	
       
      }
        mViewPager.setFocusable(true);
        mViewPager.setAdapter(new MyPagerAdapter());
        mViewPager.setOnPageChangeListener(new MyPageChangeListener());
    }
   

    private void startPlay(){
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 1, 4, TimeUnit.SECONDS);
    }
 
    @SuppressWarnings("unused")
	private void stopPlay(){
        scheduledExecutorService.shutdown();
    }
    /** 
     * 设置选中的tip的背景 
     * @param selectItems 
     */  
    private void setImageBackground(int selectItems){  
        for(int i=0; i<dotViewsList.size(); i++){  
            if(i == selectItems){  
            	dotViewsList.get(i).setBackgroundResource(R.drawable.dot_black);  
            }else{  
            	dotViewsList.get(i).setBackgroundResource(R.drawable.dot_white);  
            }  
        }  
    }  
    private class MyPagerAdapter  extends PagerAdapter{

        @Override
        public void destroyItem(View container, int position, Object object) {
            // TODO Auto-generated method stub
            //((ViewPag.er)container).removeView((View)object);
            ((ViewPager)container).removeView(imageViewsList.get(position));
            
        }

        @Override
        public Object instantiateItem(View container, int position) {
            // TODO Auto-generated method stub
            ((ViewPager)container).addView(imageViewsList.get(position));
            return imageViewsList.get(position);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return imageViewsList.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return arg0 == arg1;
        }
        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public Parcelable saveState() {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public void startUpdate(View arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void finishUpdate(View arg0) {
            // TODO Auto-generated method stub
            
        }
        
    }
  
    
    private class MyPageChangeListener implements OnPageChangeListener{

        boolean isAutoPlay = false;

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub
            switch (arg0) {
            case 1:
                isAutoPlay = false;
                break;
            case 2:
                isAutoPlay = true;
                break;
            case 0:
                if (mViewPager.getCurrentItem() == mViewPager.getAdapter().getCount() - 1 && !isAutoPlay) {
                    mViewPager.setCurrentItem(0);
                }
                
                else if (mViewPager.getCurrentItem() == 0 && !isAutoPlay) {
                    mViewPager.setCurrentItem(mViewPager.getAdapter().getCount() - 1);
                }
                break;
        }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub
            
        }

        @Override
        public void onPageSelected(int pos) {
            // TODO Auto-generated method stub
        	 setImageBackground(pos % imageUris.size());  

        }
        
    }
    
    
    
    private class SlideShowTask implements Runnable{

        @Override
        public void run() {
            // TODO Auto-generated method stub
            synchronized (mViewPager) {
                currentItem = (currentItem+1)%imageViewsList.size();
                handler.obtainMessage().sendToTarget();
            }
        }
        
    }
 
    
    @SuppressWarnings("unused")
	private void destoryBitmaps() {

        for (int i = 0; i < imageViewsList.size(); i++) {
            ImageView imageView = imageViewsList.get(i);
            Drawable drawable = imageView.getDrawable();
            if (drawable != null) {
                
                drawable.setCallback(null);
            }
        }
    }
    
}


说过自定义控件的布局和相应类之后,我们就要来使用它了,那么我们怎么去使用这个呢,请看下面的内容。
在你的工程中如果想要使用该自定义控件,你需要把自定义控件的布局文件拷贝到你的layout文件夹下,然后将上面的类拷贝到你的工程里去,在你自己的布局文件中这样引用该控件,代码,如下:


 <com.gc.view.SlideShowView
       android:id="@+id/slideshowView"
       android:layout_width="fill_parent"
       android:layout_height="140dp"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"  
       
    />
<!--com.gc.view是SlideShowView所在的包名,大家使用时需把此包名换成自己的包名-->
然后在相应的Activity或Fragment中这样动态设置图片:
(1)先通过findviewbyid获得该控件】

(2)调用该控件的setImageUris的方法

具体代码如下所示:

	<span style="white-space:pre">	</span>List<String> imageUris=new ArrayList<String>();
		imageUris.add("http://e.hiphotos.baidu.com/image/pic/item/d6ca7bcb0a46f21ffac59520f4246b600d33aed4.jpg");
		imageUris.add("http://a.hiphotos.baidu.com/image/pic/item/ac345982b2b7d0a2549f27eac9ef76094b369a76.jpg");
		imageUris.add("http://b.hiphotos.baidu.com/image/pic/item/d52a2834349b033b12e5c3c317ce36d3d539bdbd.jpg");
		imageUris.add("assets://one.jpg");
		imageUris.add("assets://two.jpg");
		imageUris.add("assets://three.jpg");//上面代码是初始化图片的URI路径
<span style="font-family:Arial, Helvetica, sans-serif;"><span style="white-space:pre">			</span>     mSlideShowView=(SlideShowView)findViewById(R.id.slideshowView);</span>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre">			</span>     mSlideShowView.setImageUris(imageUris);</span>
然后在应用程序中的效果如下:
bubuko.com,布布扣
好了,该自定义控件的使用就是这样的。相信大家也应该明白了,如果有不对的地方欢迎指出,或者有不明白可以回复留言。

转载请注明出处:http://blog.csdn.net/android_jiangjun/article/details/39638129


Android自定义控件之应用程序首页轮播图

标签:android应用   自定义控件   viewpager   首页轮播   uri   

原文地址:http://blog.csdn.net/android_jiangjun/article/details/39638129

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!