無限輪播

要實現無限輪播:viewpager+handler


項目結構圖如下:

項目創建

一、首先在佈局文操作

1、activity_main.xml如下展示:

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <android.support.v4.view.ViewPager
            android:id="@+id/vp"
            android:layout_width="match_parent"
            android:layout_height="200dp" />

        <LinearLayout
            android:id="@+id/ll_dot"
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@id/vp"
            android:layout_centerHorizontal="true" >
        </LinearLayout>
    </RelativeLayout>


</LinearLayout>

2、在創建vp_item.xml

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

    <ImageView
        android:id="@+id/vp_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

二、在java文件操作

1、MainActivity.class

package com.example.viepager;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;

import com.example.viepager.VPBean.Items;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class MainActivity extends Activity {
	private ArrayList<Items> iv_list;
	private List<ImageView> imgList = new ArrayList<ImageView>();
	private ViewPager vp;
	private String url = "http://i.dxy.cn/snsapi/event/count/list/all";
	private VP_Adapter adapter;
	Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			int num = msg.what;
			switch (num) {
			case 0:
				setdot();
				ArrayList<Items> iv_list = (ArrayList<Items>) msg.obj;
				vp.setCurrentItem(iv_list.size());
				adapter = new VP_Adapter(iv_list, MainActivity.this, handler);
				vp.setAdapter(adapter);
				sendDelayMessage();
				break;
			case 1:

				int currentItem = vp.getCurrentItem();
				currentItem++;
				vp.setCurrentItem(currentItem);
				sendDelayMessage();
				break;
			default:
				break;
			}
		}

		
	};
	private LinearLayout ll_dot;
	  protected void setdot() {
	        if (imgList != null) {
	            imgList.clear();
	        }

	        for (int i = 0; i < iv_list.size(); i++) {
	            ImageView img_dot = new ImageView(MainActivity.this);
	            if (i == 0) {
	                img_dot.setImageResource(R.drawable.page_shape);
	            } else {
	                img_dot.setImageResource(R.drawable.page_shape_no);

	            }
	            LayoutParams params = new LayoutParams(10, 5);
	            params.setMargins(5, 0, 5, 0);

	            imgList.add(img_dot);
	            ll_dot.addView(img_dot, params);
	        }
	    }

	    protected void sendDelayMessage() {
	        // TODO Auto-generated method stub
	        handler.sendEmptyMessageDelayed(1, 2000);
	    }
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 獲得控件
		findByID();
		// 設置適配器

		// 獲取數據源
		getDatas();
		//viewpager的點擊事件
		viewpagerListener();
	}

	private void viewpagerListener() {
		// TODO Auto-generated method stub
		vp.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int arg0) {
				// TODO Auto-generated method stub
				 for (int i = 0; i < imgList.size(); i++) {
	                    if (arg0 % iv_list.size() == i) {
	                        imgList.get(arg0 % iv_list.size()).setImageResource(
	                                R.drawable.page_shape);
	                    } else {
	                        imgList.get(i).setImageResource(
	                                R.drawable.page_shape_no);
	                    }
	                }
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	private void getDatas() {
		// TODO Auto-generated method stub
		HttpUtils httpUtils = new HttpUtils();
		httpUtils.send(HttpMethod.GET, url, new RequestCallBack<String>() {

			

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				// TODO Auto-generated method stub
				String json = arg0.result;
				Gson gson = new Gson();
				VPBean vpBean = gson.fromJson(json, VPBean.class);
				iv_list = vpBean.items;
				Message message = new Message();
				message.obj = iv_list;
				handler.sendMessage(message);
			}
		});
	}

	private void findByID() {
		vp = (ViewPager) findViewById(R.id.vp);
		ll_dot = (LinearLayout)findViewById(R.id.ll_dot);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

2、設配器VP_Adapter.class

package com.example.viepager;

import java.util.ArrayList;

import android.content.Context;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.example.viepager.VPBean.Items;
import com.nostra13.universalimageloader.core.ImageLoader;

public class VP_Adapter extends PagerAdapter{

	private ArrayList<Items> items;
	private Context context;
	private Handler handler;
	


	public VP_Adapter(ArrayList<Items> items, Context context, Handler handler) {
		super();
		this.items = items;
		this.context = context;
		this.handler = handler;
	}

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

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

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

	 @Override
	    public Object instantiateItem(ViewGroup container, final int position) {
	        // TODO Auto-generated method stub
	        View view = View.inflate(context, R.layout.vp_item, null);
	        ImageView iv_home_page = (ImageView) view
	                .findViewById(R.id.vp_image);
	        iv_home_page.setOnClickListener(new View.OnClickListener() {

	            @Override
	            public void onClick(View v) {
	                // TODO Auto-generated method stub
	           /*     handler.removeCallbacksAndMessages(null);
	                handler.sendEmptyMessageDelayed(1, 2000);
	                String d = data.get(position%data.size()).url;

	                Intent intent = new Intent(context, ViewPager_Activity.class);
	                intent.putExtra("Ad1", d);
	                Activity activity = (Activity) context;
	                activity.startActivity(intent);*/

	            }
	        });
	        ImageLoader.getInstance().displayImage(
	        		items.get(position % items.size()).path, iv_home_page);
	        container.addView(view);
	        return view;
	    }

}

3、封裝的bean包   VPBean.class

package com.example.viepager;

import java.util.ArrayList;

public class VPBean {

	public ArrayList<Items> items;
	public class Items{
		public String url;
		public String path;
	}
}

4、ImageUtils.class

package com.example.viepager;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import android.app.Application;

public class ImageUtils extends Application {
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		  //創建默認的ImageLoader配置參數 
        ImageLoaderConfiguration configuration = ImageLoaderConfiguration 
                .createDefault(this); 
           
        //Initialize ImageLoader with configuration. 
        ImageLoader.getInstance().init(configuration);  
	}
}

三、在libs導入.jar包

gson-2.2.4.jar

universal-image-loader-1.9.5.jar

xUtils-2.4.4.jar


四、res文件下創建drawable文件

1、page_shape_no.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
     <corners android:radius="8dp"/>
    <solid android:color="#FF66B6"/> 

</shape>

2、page_shape.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
        <!-- 設置小圓點的半徑 -->
    <corners android:radius="3dp"/>
    
    <!-- 設置小圓點爲展示時的顏色 -->
    <solid android:color="#0f0"/>

</shape>

五、清單文件有一些操作  AndroidManifest.xml

不要忘配置權限:<uses-permission android:name="android.permission.INTERNET"/>

還要注意的一點我這你使用ImageLoader加載圖片繼承application的,需要AndroidManifest.xml的application設置  android:name="com.example.viepager.ImageUtils"

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章