Viewpager实现网络图片的轮播
//主意:里面用到了第三方的Xutils.jar包和Imageloader.jar包还用到了访问网络,所以要加网络权限
<uses-permission android:name="android.permission.INTERNET"/>
//---------------------主布局文件---------------------------------------
<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">
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="200dp">
<android.support.v4.view.ViewPager
android:layout_width="fill_parent"
android:layout_height="200dp"
android:id="@+id/vp_viewpager"></android.support.v4.view.ViewPager>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="25dp"
android:id="@+id/ll_LinearLayout"
android:orientation="horizontal"
android:layout_alignBottom="@+id/vp_viewpager"
android:gravity="center"></LinearLayout>
</RelativeLayout>
</LinearLayout>
//-------------在res目录下新建一个drawable文件夹,在文件夹下创建XML文件,选中shape类型,创建了名字叫dot_focuse.xml和dot_normal.xml---------------------------------
//-------------dot_focuse.xml 中----------------
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="9dp"/>
<solid android:color="#fff"/>
</shape>
//------------------dot_normal.xml中-----------------
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="9dp"/>
<solid android:color="#88000000"/>
</shape>
//-----------------------自定义的适配器-----------------------------------------
package com.example.lunbo;
import java.util.List;
import android.content.Context;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
public class MyPagerAdapter extends PagerAdapter{
//封装
private List<ImageView> imageList;
private Context context;
private Handler handler;
//有参构造
public MyPagerAdapter(List<ImageView> imageList, Context context,
Handler handler) {
super();
this.imageList = imageList;
this.context = context;
this.handler = handler;
}
@Override
public int getCount() {
//返回最大值
return Integer.MAX_VALUE;
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0==arg1;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
// 通过控件集合获取imageView 添加到容器中,并作为key 返回
ImageView imageView = imageList.get(position % imageList.size());
imageView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
// 当按下的时候,停止轮播
case MotionEvent.ACTION_DOWN:
// 移除所有的回调和消息
handler.removeCallbacksAndMessages(null);
break;
// 抬起
case MotionEvent.ACTION_UP:
handler.sendEmptyMessageDelayed(0, 2000);
break;
// 取消的时候,继续开始录播
case MotionEvent.ACTION_CANCEL:
handler.sendEmptyMessageDelayed(0, 2000);
break;
default:
break;
}
//触摸事件不被消费,true 消费该触摸事件
return true;
}
});
container.addView(imageView);
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
//移除
container.removeView((View) object);
}
}
//------------------bean包中的goods--------------------------------
package com.example.lunbo;
public class Goods {
private String id;
private String image;
public Goods(String id, String image) {
super();
this.id = id;
this.image = image;
}
public Goods() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Override
public String toString() {
return "Goods [id=" + id + ", image=" + image + "]";
}
}
//===============一下是mainActivity中===========================
package com.example.lunbo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.lidroid.xutils.BitmapUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
public class MainActivity extends Activity {
private String urlPath = "http://m.yunifang.com/yunifang/mobile/home?random=17257&encode=56f7b9f64804f3c6423bb3ee62eab517";
private List<Goods> goods = new ArrayList<Goods>();
private List<ImageView> imageList = new ArrayList<ImageView>();
private List<ImageView> dotList = new ArrayList<ImageView>();
private ViewPager vp_viewpager;
private LinearLayout ll_LinearLayout;
private MyPagerAdapter adapter;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
// 先去获取到当前条目索引
int currentItem = vp_viewpager.getCurrentItem();
// 条目索引+1
currentItem++;
// 重新设置给viewPager
vp_viewpager.setCurrentItem(currentItem);
// 再调用发延时消息的方法
sendDelayMessage();
break;
case 1:
// 获得数据
String text = (String) msg.obj;
// 解析数据
tojson(text);
break;
default:
break;
}
}
};
// ------------------------------------
// 解析数据
private void tojson(String text) {
try {
JSONObject obj = new JSONObject(text);
JSONObject data = obj.getJSONObject("data");
JSONArray ad1 = data.getJSONArray("ad1");
for (int i = 0; i < ad1.length(); i++) {
JSONObject json = ad1.getJSONObject(i);
String id = json.getString("id");
String image = json.getString("image");
// 把解析的数据添加到集合
Goods goodss = new Goods(id, image);
goods.add(goodss);
}
// 初始化图片
initImageview();
// 初始化小圆点
initDots();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
// -------------------------------
// 初始化图片 此方法需要用到第三方的Xuitlsjar包
private void initImageview() {
// 先使用xutils的工具类
BitmapUtils bitmapUtils = new BitmapUtils(this);
// 遍历商品的集合
for (int i = 0; i < goods.size(); i++) {
// 创建imageView 并通过工具类将图片设置到控件上
ImageView imageView = new ImageView(this);
bitmapUtils.display(imageView, goods.get(i).getImage());
// 添加到Imageview的集合中
imageList.add(imageView);
}
// 设置适配器
adapter = new MyPagerAdapter(imageList, this, handler);
vp_viewpager.setAdapter(adapter);
}
/*
* 此方法需要用到第三方的Imageloader.jar包
*/
/*// 初始化图片
private void initImageview() {
// 遍历商品的集合
for (int i = 0; i < goods.size(); i++) {
// 创建imageView 并通过工具类将图片设置到控件上
ImageView imageView = new ImageView(this);
//bitmapUtils.display(imageView, goods.get(i).getImage());
ImageLoader.getInstance().init(
ImageLoaderConfiguration.createDefault(this));
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisk(true).build();
ImageLoader.getInstance().displayImage(
goods.get(i).getImage(), imageView, options);
// 添加到Imageview的集合中
imageList.add(imageView);
}
// 设置适配器
adapter = new MyPagerAdapter(imageList, this, handler);
vp_viewpager.setAdapter(adapter);
}*/
/**
* 发送延时消息
*/
private void sendDelayMessage() {
handler.sendEmptyMessageDelayed(0, 2000);
}
// ---------------------------------
// 初始化小圆点
private void initDots() {
dotList.clear();
for (int i = 0; i < goods.size(); i++) {
ImageView imageView = new ImageView(this);
if (i == 0) {
// 如果是第一张,默认给一个亮的小点
imageView.setImageResource(R.drawable.dot_focuse);
} else {
// 如果不是滴一个,默认给一个暗的小点
imageView.setImageResource(R.drawable.dot_normal);
}
// 设置小点的默认宽高为20dp 导入LinearLayout包
LayoutParams params = new LayoutParams(10, 10);
// 设置小点的间距
params.setMargins(5, 0, 5, 0);
ll_LinearLayout.addView(imageView, params);
// 往小点集合中添加view
dotList.add(imageView);
}
}
// ------------------------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 找到控件
vp_viewpager = (ViewPager) findViewById(R.id.vp_viewpager);
ll_LinearLayout = (LinearLayout) findViewById(R.id.ll_LinearLayout);
// 获得网络数据
huodeshuju();
// 设置初始的展示条目
vp_viewpager.setCurrentItem(imageList.size() * 1000000);
// 设置延时切换
sendDelayMessage();
// 设置viewpager的滑动监听事件
vp_viewpager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int arg0) {
// 遍历小点的集合
for (int i = 0; i < dotList.size(); i++) {
// 如果当前的索引值和i相等
if (arg0 % dotList.size() == i) {
// 设置小点为亮色
dotList.get(i).setImageResource(R.drawable.dot_focuse);
} else {
// 否则暗色
dotList.get(i).setImageResource(R.drawable.dot_normal);
}
}
}
@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 huodeshuju() {
// 使用线程
new Thread() {
public void run() {
try {
// 先创建出了一个URL对象,urlPath:是我们访问接口地址
URL url = new URL(urlPath);
// URL链接对象,通过URL对象打开一个connection链接对像
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
// 设置urlConnection对象链接超时
urlConnection.setConnectTimeout(5000);
// 设置urlConnection对象获取数据超时
urlConnection.setReadTimeout(5000);
// 设置本次urlConnection请求方式
urlConnection.setRequestMethod("GET");
// 调用urlConnection的链接方法,线程等待,等待的是服务器所给我们返回的结果集
urlConnection.connect();
// 获取本次网络请求的状态码
int code = urlConnection.getResponseCode();
// 如果本次返回的状态吗是200(成功)
if (code == 200) {
// 调用urlConnection.getInputStream得到本次请求所返回的结果流
InputStream inputStream = urlConnection
.getInputStream();
// 创建一个BufferedReader,去读取结果流
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String readLine;
StringBuffer buffer = new StringBuffer();
while ((readLine = reader.readLine()) != null) {
buffer.append(readLine);
}
// 读取完结果流之后所得到的结果
String result = buffer.toString();
Log.i("数据:", result);
Message message = new Message();
message.what = 1;
message.obj = result;
handler.sendMessage(message);
inputStream.close();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
}