请参见最新的代码:
http://blog.csdn.net/lfdfhl/article/details/50900530
http://blog.csdn.net/lfdfhl/article/details/50900497
http://blog.csdn.net/lfdfhl/article/details/50900423
MainActivity如下:
package com.example.testviewpager; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.GestureDetector; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.animation.Interpolator; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; /** * Demo描述: * ViewPager显示图片 * 要求: * 1 图片来自于网络 * 2 ViewPager无限循环播放图片 * 3 ViewPager亦可手指滑动且与自动播放不冲突 * * Bug描述: * 如果图片数量小于等于三张,那么会出现以下bug: * 当进入应用后手指立马从左往右滑动图片,此时会显示空白 * 解决办法: * 如果图片数量小于等于三张,不执行PagerAdapter中的destroyItem()方法 */ public class MainActivity extends Activity { private ViewPager mViewPager; private ArrayList<View> mSucViewPagerItemsList; private ViewGroup mContentView, mPointsView; private ImageView[] mPointImageViews; private String mRawImageUrlsArray[]; private Timer mTimer; private int mPosition = 0; private boolean isOnCreate = true; public int mRawImageUrlsFinishCount = 0; private Downloader mDownloader; private final int DOWNLOAD_FINISH = -1999; private boolean isSuccess = true; private ViewPagerAdapter mViewPagerAdapter; private ProgressBar mProgressBar; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //开始进入界面的时候就显示内容 setContentView(R.layout.main); init(); } private void init() { new Thread() { public void run() { Util.cleanCache(); initViewPagerItems(); }; }.start(); LayoutInflater inflater = this.getLayoutInflater(); mContentView = (ViewGroup) inflater.inflate(R.layout.main,null); mPointsView = (ViewGroup) mContentView.findViewById(R.id.home_points_layout); } @Override protected void onRestart() { super.onRestart(); initTimer(); } protected void onPause() { super.onPause(); if (mTimer != null) { mTimer.cancel(); mTimer = null; } } Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { if (msg.what == DOWNLOAD_FINISH) { if (mSucViewPagerItemsList.size() != 0) { initPointsView(); initViewPager(); initTimer(); } //等所有东西初始化完成,再显示界面的内容 //setContentView(R.layout.main);//该句错误,应该使用下一句 setContentView(mContentView); mProgressBar=(ProgressBar) findViewById(R.id.home_progressBar); mProgressBar.setVisibility(View.GONE); } else { try { Field mScroller; mScroller = ViewPager.class.getDeclaredField("mScroller"); mScroller.setAccessible(true); Field interpolator = ViewPager.class.getDeclaredField("sInterpolator"); interpolator.setAccessible(true); FixedSpeedScroller scroller = new FixedSpeedScroller(mViewPager.getContext(),(Interpolator) interpolator.get(null)); mScroller.set(mViewPager, scroller); } catch (Exception e) { } mViewPager.setCurrentItem(msg.what, true); } }; }; private void initViewPager() { mViewPager = (ViewPager) mContentView.findViewById(R.id.home_viewPager); mViewPagerAdapter=new ViewPagerAdapter(mSucViewPagerItemsList); mViewPager.setAdapter(mViewPagerAdapter); mViewPager.setOnPageChangeListener(new MizunoOnPageChangeListener()); final GestureDetector tapGestureDetector = new GestureDetector(this,new TapGestureListener()); mViewPager.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { System.out.println(" 手指抬起 "); initTimer(); } tapGestureDetector.onTouchEvent(event); return false; } }); } private void initTimer() { if (isOnCreate) { mViewPager.setCurrentItem(200 * mRawImageUrlsArray.length, true); mPosition = (200 * mRawImageUrlsArray.length); isOnCreate = false; } else { mViewPager.setCurrentItem(mPosition, true); } mTimer = new Timer(); mTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { mPosition++; handler.sendEmptyMessage(mPosition); } }, 3000, 2000); } class TapGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onSingleTapConfirmed(MotionEvent e) { System.out.println(" TapGestureListener "); return false; } @Override public boolean onDown(MotionEvent e) { if (mTimer != null) { mTimer.cancel(); mTimer = null; } return super.onDown(e); } } private void initViewPagerItems() { View itemView = null; ImageView imageView = null; mSucViewPagerItemsList = new ArrayList<View>(); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); mRawImageUrlsArray = this.getResources().getStringArray(R.array.testPathArray); mDownloader = new Downloader(MainActivity.this); for (int i = 0; i < mRawImageUrlsArray.length; i++) { String path=mDownloader.download(mRawImageUrlsArray[i]); Bitmap bitmap=null; if (path!=null) { bitmap = BitmapFactory.decodeFile(path); } if (bitmap == null) { isSuccess = false; } else { isSuccess = true; } if (isSuccess) { itemView = inflater.inflate(R.layout.viewpage_item, null); imageView = (ImageView) itemView.findViewById(R.id.viewPage_item_imageView); imageView.setImageBitmap(bitmap); mSucViewPagerItemsList.add(itemView); } if (i == mRawImageUrlsArray.length - 1) { handler.sendEmptyMessage(DOWNLOAD_FINISH); } } } /** * Instant pointView * */ private void initPointsView() { mPointImageViews = new ImageView[mSucViewPagerItemsList.size()]; for (int i = 0; i < mSucViewPagerItemsList.size(); i++) { ImageView imageView = new ImageView(MainActivity.this); imageView.setLayoutParams(new LayoutParams(10, 10)); TextView mPointTextView = new TextView(MainActivity.this); mPointTextView.setLayoutParams(new LayoutParams(10, 10)); imageView.setPadding(10, 0, 10, 0); mPointImageViews[i] = imageView; if (i == 0) { mPointImageViews[i] .setBackgroundResource(R.drawable.icon_current); } else { mPointImageViews[i] .setBackgroundResource(R.drawable.icon_slide); } mPointsView.addView(mPointImageViews[i]); if (i != mSucViewPagerItemsList.size() - 1) { mPointsView.addView(mPointTextView); } } } // Monitor this ViewPager status change class MizunoOnPageChangeListener implements OnPageChangeListener { private int pointIndex; public void onPageScrollStateChanged(int arg0) { } public void onPageScrolled(int arg0, float arg1, int arg2) { } public void onPageSelected(int currentItem) { mPosition = currentItem;// very important pointIndex = currentItem % mSucViewPagerItemsList.size(); for (int i = 0; i < mPointImageViews.length; i++) { mPointImageViews[pointIndex] .setBackgroundResource(R.drawable.icon_current); if (pointIndex != i) { mPointImageViews[i] .setBackgroundResource(R.drawable.icon_slide); } } } } protected void initPush() {} protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); } @Override protected void onResume() { super.onResume(); // initTimer(); // this. appVisor.openTracking(); // appVisor.trackPage("夋柺侾"); } @Override protected void onDestroy() { super.onDestroy(); } }
Downloader如下:
package com.example.testviewpager; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.content.Context; import android.graphics.Bitmap; import android.net.Uri; import android.os.Environment; public class Downloader { private Context mContext; private String mPath; private Bitmap mBitamp=null; private HttpClient mHttpClient; private File imagesDir; private String mDir="mizunopics"; private final String FILE_SUFFIX="mizuno"; public Downloader(Context context) { super(); this.mContext = context; //this.mPath = path; if (Util.isSDCardExist()) { String SDCardPath=Environment.getExternalStorageDirectory().toString(); imagesDir = new File(SDCardPath+ File.separator + mDir); } if (imagesDir != null && !imagesDir.exists()) { Util.doMkdir(imagesDir); } } public String download(String path){ this.mPath = path; try { File file = getFromSDcard(mPath); if (file.exists()) { return file.getAbsolutePath(); }else{ file.createNewFile(); mHttpClient = new DefaultHttpClient(); final HttpGet getRequest = new HttpGet(mPath); HttpResponse httpResponse = mHttpClient.execute(getRequest); int statusCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null&&statusCode==HttpStatus.SC_OK) { InputStream inputStream = null; long size = httpEntity.getContentLength(); inputStream = httpEntity.getContent(); saveToSDCard(mPath,inputStream, size); System.out.println("下载完成,保存路径为:"+file.getAbsolutePath()); return file.getAbsolutePath(); }else { return null; } } } catch (Exception e) { return null; }finally{ if (mHttpClient != null) { mHttpClient.getConnectionManager().shutdown(); } } //return null; } public void saveToSDCard(String url, InputStream inputStream, long size) { OutputStream outputStream = null; try { if (!Util.canSave(size)) { return ; } File file = getFromSDcard(url); if (!file.exists()) { file.createNewFile(); } outputStream = new FileOutputStream(file); copyStream(inputStream, outputStream); } catch (Exception e) { return; } finally { if (outputStream != null) { try { //outputStream.close(); //inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } } public File getFromSDcard(String url) { String fileName = getImageNameFromUrl(url); if (imagesDir == null) { return null; } File file = new File(imagesDir, fileName); //System.out.println("getFromSDcard file.getPath()="+file.getPath()); return file; } private String getImageNameFromUrl(String url) { Uri uri = Uri.parse(url); String imageName = uri.getLastPathSegment()+FILE_SUFFIX; return imageName; } private void copyStream(InputStream inputStream, OutputStream outputStream) { final int buffer_size = 1024; try { byte[] bytes = new byte[buffer_size]; for (;;) { int count = inputStream.read(bytes, 0, buffer_size); if (count == -1) break; outputStream.write(bytes, 0, count); } } catch (Exception ex) { }finally{ try { inputStream.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
FixedSpeedScroller如下:
package com.example.testviewpager; import android.content.Context; import android.view.animation.Interpolator; import android.widget.Scroller; public class FixedSpeedScroller extends Scroller { private int mDuration = 1000; public FixedSpeedScroller(Context context) { super(context); } public FixedSpeedScroller(Context context, Interpolator interpolator) { super(context, interpolator); } @Override public void startScroll(int startX, int startY, int dx, int dy, int duration) { // Ignore received duration, use fixed one instead super.startScroll(startX, startY, dx, dy, mDuration); } @Override public void startScroll(int startX, int startY, int dx, int dy) { // Ignore received duration, use fixed one instead super.startScroll(startX, startY, dx, dy, mDuration); } }
ViewPagerAdapter如下:
package com.example.testviewpager; import java.util.ArrayList; import android.os.Parcelable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; public class ViewPagerAdapter extends PagerAdapter { private ArrayList<View> mViewPagerItemsList; public ViewPagerAdapter(ArrayList<View> mViewPagerItemsList) { super(); this.mViewPagerItemsList = mViewPagerItemsList; } @Override public void startUpdate(View arg0) { } @Override public int getCount() { // return mViewPagerItemsList.size(); return Integer.MAX_VALUE; } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } @Override public int getItemPosition(Object object) { return super.getItemPosition(object); } // a page is Initialization @Override public Object instantiateItem(View arg0, int arg1) { System.out.println("初始化ViewPager的第"+arg1+"个Item"); if (arg1 >= mViewPagerItemsList.size() - 1) { int newPosition = arg1 % mViewPagerItemsList.size(); arg1 = newPosition; } else if (arg1 < 0) { arg1 = (-arg1) % mViewPagerItemsList.size(); } try { ((ViewPager) arg0).addView(mViewPagerItemsList.get(arg1), 0); } catch (Exception e) { } //Log.e("instantiateItem", "arg1 after == " + arg1); return mViewPagerItemsList.get(arg1); } @Override public void destroyItem(View arg0, int arg1, Object arg2) { //Log.e("destroyItem", "arg1 before == " + arg1); System.out.println("删除掉ViewPager的第"+arg1+"个Item"); if (arg1 >= mViewPagerItemsList.size() - 1) { int newPosition = arg1 % mViewPagerItemsList.size(); arg1 = newPosition; } else if (arg1 < 0) { arg1 = (-arg1) % mViewPagerItemsList.size(); } try { //Log.e("destroyItem", "arg1 after == " + arg1); if (mViewPagerItemsList.size()<4) { System.out.println("===》没有执行destroyItem"); } else { System.out.println("===》执行destroyItem"); ((ViewPager) arg0).removeView(mViewPagerItemsList.get(arg1)); } } catch (Exception e) { e.printStackTrace(); } } @Override public void finishUpdate(View arg0) { } @Override public void restoreState(Parcelable arg0, ClassLoader arg1) { } @Override public Parcelable saveState() { return null; } }
Util如下:
package com.example.testviewpager; import java.io.File; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Environment; import android.os.StatFs; public class Util { private static final int ERROR = -1; public static int save_dir = 1; public static String UUID_KEY = "uuid_key"; public static String CONFIG = "config_file"; public static String imagesDir="mizunopics"; public static void cleanCache() { String SDCardPath=Environment.getExternalStorageDirectory().toString(); File cacheFile=new File(SDCardPath+ File.separator + imagesDir); if (cacheFile.exists()) { String files[]=cacheFile.list(); File imageFile=null; for (int i = 0; i < files.length; i++) { imageFile=new File(cacheFile.getAbsolutePath()+File.separator+files[i]); if (imageFile.exists()) { System.out.println("====删除缓存图片====> path="+imageFile.getAbsolutePath()); imageFile.delete(); } } //cacheFile.delete(); } } public static boolean isNetworkAvailable(Context context) { ConnectivityManager connm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connm == null) { return false; } else { NetworkInfo[] nis = connm.getAllNetworkInfo(); if (nis != null) { for (int i = 0; i < nis.length; i++) { if (nis[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; } public static boolean doMkdir(File dirFile) { try { boolean bFile = dirFile.exists(); if (bFile == true) { return true; } else { bFile = dirFile.mkdirs(); if (bFile == true) { return true; } else { return false; } } } catch (Exception err) { err.printStackTrace(); return false; } } public static boolean isSDCardExist() { return android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED); } public static long getAvailableExternalMemorySize() { if (isSDCardExist()) { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return availableBlocks * blockSize; } else { return ERROR; } } public static boolean canSave(long size) { return getAvailableExternalMemorySize() > size; } }
main.xml如下:
<?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:background="#eee" > <TextView android:id="@+id/home_textView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="完美的ViewPager" android:textSize="25sp" android:gravity="center" /> <RelativeLayout android:id="@+id/home_FrameLayout" android:layout_width="wrap_content" android:layout_height="240dip" android:layout_below="@id/home_textView" android:layout_marginLeft="20dip" android:layout_marginRight="20dip" > <ProgressBar android:id="@+id/home_progressBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" /> <android.support.v4.view.ViewPager android:id="@+id/home_viewPager" android:layout_width="wrap_content" android:layout_height="240dip" android:layout_centerHorizontal="true" /> </RelativeLayout> <RelativeLayout android:id="@+id/home_points_rl" android:layout_width="fill_parent" android:layout_height="60dip" android:layout_below="@id/home_FrameLayout" > <LinearLayout android:id="@+id/home_points_layout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:orientation="horizontal" > </LinearLayout> </RelativeLayout> </RelativeLayout>
<?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:orientation="vertical" > <ImageView android:id="@+id/viewPage_item_imageView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" /> </RelativeLayout>