Android通过ViewPager实现左右滑动切换图片
想开发像人人网相册打开单张图片时候能左右滑动切换图片的效果,开始通过FlipperView实现,不能跟手拖动,效果不好,而且需要自己写很多代码来控制FlipperView中的View。后来发现Android 3.0之后的SDK中提供了android-support-v4包用以实现版本兼容,让老版本系统下的应用通过加入jar包实现扩展,得到新版的各种技术优势,例如Fragment等。
ViewPager是android-support-v4.jar包中的一个系统控件,继承自ViewGroup,专门用以实现左右滑动切换View的效果,使用时需要首先在Project->properties->Java Build Path->Libraries->Add External Jars中加入sdk目录下的extras/android/support/v4/android-support-v4.jar(如果找不到,则需要用sdk manager下载android support package)。加入这个jar包之后就可以使用ViewPager类了。
ViewPager的使用类似于ListView,需要有对应的Adapter进行数据绑定,实现图片切换仅需要继承PaperAdapter就可以了。继承后需要重写如下四个方法。
instantiateItem(ViewGroup, int)
destroyItem(ViewGroup, int, Object)
getCount()
isViewFromObject(View, Object)
import java.io.FileNotFoundException;import java.util.List;import android.content.Context;import android.graphics.Bitmap;import android.net.Uri;import android.support.v4.view.PagerAdapter;import android.support.v4.view.ViewPager;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;public class TestAdapter extends PagerAdapter { private List<String> mPaths; private Context mContext; public TestAdapter(Context cx) { mContext = cx.getApplicationContext(); } public void change(List<String> paths) { mPaths = paths; } @Override public int getCount() { // TODO Auto-generated method stub return mPaths.size(); } @Override public boolean isViewFromObject(View view, Object obj) { // TODO Auto-generated method stub return view == (View) obj; } @Override public Object instantiateItem (ViewGroup container, int position) { ImageView iv = new ImageView(mContext); try { Bitmap bm = BitmapFactory.decodeFile(mPaths.get(position));//载入bitmap iv.setImageBitmap(bm); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (OutOfMemoryError e) { // TODO Auto-generated catch block e.printStackTrace(); } ((ViewPager)container).addView(iv, 0); return iv; } @Override public void destroyItem (ViewGroup container, int position, Object object) { container.removeView((View)object); }}
<android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="fill_parent" android:layout_height="fill_parent" />
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mViewPager = (ViewPager)findViewById(R.id.pager); mAdapter = new TestAdapter(this); mViewPager.setAdapter(mAdapter); mAdapter.change(getList()); } private List<String> getList() { List<String> list = new ArrayList<String>(); list.add("file:///sdcard/Sunset.jpg"); list.add("file:///sdcard/Winter.jpg"); list.add("file:///sdcard/Water lilies.jpg"); list.add("file:///sdcard/Blue hills.jpg"); return list; }