广告轮播2
1、权限
<uses-permission android:name="android.permission.INTERNET"/>
2、视图
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" 6 > 7 <android.support.v4.view.ViewPager 8 android:id="@+id/vp" 9 android:layout_width="match_parent" 10 android:layout_height="match_parent" 11 android:layout_weight="1" 12 > 13 </android.support.v4.view.ViewPager> 14 15 <LinearLayout 16 android:layout_width="wrap_content" 17 android:layout_height="wrap_content" 18 android:id="@+id/ll" 19 android:orientation="horizontal" 20 android:layout_gravity="center_horizontal" 21 > 22 23 </LinearLayout> 24 <TextView 25 android:layout_width="match_parent" 26 android:layout_height="match_parent" 27 android:layout_weight="1" 28 /> 29 </LinearLayout>
3、MainActivity代码
1 package com.zyhui.zyh_adv2; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.net.HttpURLConnection; 6 import java.net.URL; 7 import java.util.ArrayList; 8 import java.util.List; 9 10 import android.os.AsyncTask; 11 import android.os.Bundle; 12 import android.os.Handler; 13 import android.support.v4.view.PagerAdapter; 14 import android.support.v4.view.ViewPager; 15 import android.support.v4.view.ViewPager.OnPageChangeListener; 16 import android.util.Log; 17 import android.view.View; 18 import android.view.ViewGroup; 19 import android.widget.ImageView; 20 import android.widget.LinearLayout; 21 import android.app.Activity; 22 import android.graphics.Bitmap; 23 import android.graphics.BitmapFactory;
//============================================
//1、要理解往ViewPager中加载广告图片
//2、广告图片切换时,下面的小圆圈跟着切换
//3、广告相隔一定的时间,自动切换
//
//注意初始化视图时所做的事情
//============================================
24 25 public class MainActivity extends Activity implements OnPageChangeListener { 26 private ViewPager vp; 27 private LinearLayout ll; 28 private List<ImageView> views; 29 private List<Banner> banners; 30 private int currentIndex = 300; 31 private long lastTime; 32 private MyAdapter adapter; 33 private Handler handler = new Handler(); 34 private Runnable run = new Runnable(){ 35 @Override 36 public void run() { 37 if(System.currentTimeMillis() - lastTime > 1000){ 38 currentIndex++; 39 vp.setCurrentItem(currentIndex);//实现自动切换的方法 40 //Log.i("zyh",currentIndex+"--aakk"); 41 lastTime = System.currentTimeMillis(); 42 } 43 44 handler.postDelayed(run, 1000); 45 } 46 }; 47 48 @Override 49 protected void onCreate(Bundle savedInstanceState) { 50 super.onCreate(savedInstanceState); 51 setContentView(R.layout.activity_main); 52 53 initView(); 54 } 55 56 private void initView() { 57 vp = (ViewPager) findViewById(R.id.vp); 58 ll = (LinearLayout) findViewById(R.id.ll); 59 views = new ArrayList<ImageView>(); 60 banners = new ArrayList<Banner>(); 61 for(int i=0; i<5; i++){ 62 ImageView img = new ImageView(this); 63 img.setImageResource(android.R.color.white); 64 views.add(img);//广告内容 65 66 Banner banner = new Banner(); 67 banner.setUrl("http://192.168.1.100/android/adv/lmm"+(i+1)+".jpg"); 68 banners.add(banner); 69 70 //广告图片下面的小圆 71 ImageView img_circle = new ImageView(this); 72 img_circle.setImageResource(R.drawable.nomal); 73 img_circle.setPadding(10, 5, 10, 5); 74 ll.addView(img_circle); 75 76 //启动异步任务 77 MyHttpBannerTask task = new MyHttpBannerTask(); 78 task.execute(banner.getUrl(),String.valueOf(i)); 79 } 80 81 adapter = new MyAdapter(); 82 vp.setAdapter(adapter); 83 vp.setCurrentItem(300); 84 85 //通过这个的监听,来实现小圆圈切换 86 vp.setOnPageChangeListener(this); 87 88 lastTime = System.currentTimeMillis(); 89 handler.postDelayed(run, 2000);//实现自动切换方法 90 } 91 92 //PagerAdapter可以参考:http://www.tuicool.com/articles/NvuYJz 93 //和http://blog.csdn.net/harvic880925/article/details/38487149 94 private class MyAdapter extends PagerAdapter{ 95 96 //返回当前有效视图的个数 97 @Override 98 public int getCount() { 99 // TODO Auto-generated method stub 100 return Integer.MAX_VALUE; 101 } 102 103 /** 104 * 功能:该函数用来判断instantiateItem(ViewGroup, int)函数所返回来的Key与一个页面视图是否是代表的同一个视图 105 * (即它俩是否是对应的,对应的表示同一个View) 106 * 返回值:如果对应的是同一个View,返回True,否则返回False。 107 */ 108 @Override 109 public boolean isViewFromObject(View view, Object object) { 110 // TODO Auto-generated method stub 111 return view == object; 112 } 113 114 //这个函数的实现的功能是创建指定位置的页面视图 115 @Override 116 public Object instantiateItem(ViewGroup container, int position) { 117 int index = position%views.size(); 118 ((ViewPager)container).addView(views.get(index)); 119 //Log.i("zyh", position + "----bbbb"); 120 return views.get(index); 121 } 122 123 // PagerAdapter只缓存三张要显示的图片,如果滑动的图片超出了缓存的范围,就会调用这个方法,将图片销毁-已验证 124 @Override 125 public void destroyItem(ViewGroup container, int position, Object object) { 126 //Log.i("zyh", position+"--abc"); 127 ((ViewPager)container).removeView(views.get(position%views.size())); 128 } 129 } 130 131 @Override 132 public void onPageScrolled(int position, float positionOffset, 133 int positionOffsetPixels) { 134 // TODO Auto-generated method stub 135 136 } 137 138 @Override 139 public void onPageSelected(int position) { 140 currentIndex = position; 141 //Log.i("zyh",currentIndex+"--bbkk");//手主动滑动时,currentIndex才有可能变小 142 int index = position%views.size(); 143 setCurrentSelector(index); 144 lastTime = System.currentTimeMillis(); 145 } 146 147 //小圆圈切换 148 private void setCurrentSelector(int index) { 149 for(int i=0; i<ll.getChildCount(); i++){ 150 ImageView child = (ImageView) ll.getChildAt(i); 151 if(i == index){ 152 child.setImageResource(R.drawable.select); 153 }else{ 154 child.setImageResource(R.drawable.nomal); 155 } 156 } 157 } 158 159 @Override 160 public void onPageScrollStateChanged(int state) { 161 // TODO Auto-generated method stub 162 163 } 164 165 @Override 166 protected void onDestroy() { 167 super.onDestroy(); 168 handler.removeCallbacks(run); 169 } 170 171 //异步任务 172 private class MyHttpBannerTask extends AsyncTask<String, Void, Bitmap>{ 173 private int position; 174 @Override 175 protected Bitmap doInBackground(String... params) { 176 Bitmap bitmap = null; 177 String path = params[0]; 178 int position = Integer.valueOf(params[1]); 179 try { 180 bitmap = loadImageByUrl(path); 181 } catch (Exception e) { 182 // TODO Auto-generated catch block 183 e.printStackTrace(); 184 } 185 186 banners.get(position).setBitmap(bitmap); 187 this.position = position; 188 return bitmap; 189 } 190 191 @Override 192 protected void onPostExecute(Bitmap result) { 193 super.onPostExecute(result); 194 if(result != null){ 195 views.get(position).setImageBitmap(result); 196 } 197 } 198 } 199 200 public Bitmap loadImageByUrl(String path){ 201 //Log.i("zyh", path); 202 Bitmap bitmap = null; 203 try { 204 URL url = new URL(path); 205 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 206 conn.setRequestMethod("GET"); 207 conn.setReadTimeout(5000); 208 int code = conn.getResponseCode(); 209 //Log.i("zyh", code + ""); 210 if(code == 200){ 211 InputStream is = conn.getInputStream(); 212 bitmap = BitmapFactory.decodeStream(is); 213 } 214 }catch (IOException e) { 215 e.printStackTrace(); 216 } 217 return bitmap; 218 } 219 220 }
4、辅助类
1 package com.zyhui.zyh_adv2; 2 3 import android.graphics.Bitmap; 4 5 public class Banner { 6 private String url; 7 private Bitmap bitmap; 8 9 public Banner() { 10 } 11 12 public Banner(String url, Bitmap bitmap) { 13 this.url = url; 14 this.bitmap = bitmap; 15 } 16 17 18 public String getUrl() { 19 return url; 20 } 21 public void setUrl(String url) { 22 this.url = url; 23 } 24 public Bitmap getBitmap() { 25 return bitmap; 26 } 27 public void setBitmap(Bitmap bitmap) { 28 this.bitmap = bitmap; 29 } 30 31 }