在android 1.6+的版本中增加了Viewpaper类,通过这个类我们可以很简单的实现左右滑动手指切换页面,Viewpaper需要设置PaperAdapter,在PaperAdapter中实现添加或删除View的功能,具体代码:
public class AwesomePagerActivity extends Activity {
private ViewPager awesomePager;
private Context cxt;
private AwesomePagerAdapter awesomeAdapter;
private LayoutInflater mInflater;
private List<View> mListViews;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cxt = this;
awesomeAdapter = new AwesomePagerAdapter();
awesomePager = (ViewPager) findViewById(R.id.awesomepager);
awesomePager.setAdapter(awesomeAdapter);
mListViews = new ArrayList<View>();
mInflater = getLayoutInflater();
mListViews.add(mInflater.inflate(R.layout.layout1, null));
mListViews.add(mInflater.inflate(R.layout.layout2, null));
mListViews.add(mInflater.inflate(R.layout.layout3, null));
}
private class AwesomePagerAdapter extends PagerAdapter{
@Override
public int getCount() {
return mListViews.size();
}
/**
* Create the page for the given position. The adapter is responsible
* for adding the view to the container given here, although it only
* must ensure this is done by the time it returns from
* {@link #finishUpdate()}.
*
* @param container The containing View in which the page will be shown.
* @param position The page position to be instantiated.
* @return Returns an Object representing the new page. This does not
* need to be a View, but can be some other container of the page.
*/
@Override
public Object instantiateItem(View collection, int position) {
((ViewPager) collection).addView(mListViews.get(position),0);
return mListViews.get(position);
}
/**
* Remove a page for the given position. The adapter is responsible
* for removing the view from its container, although it only must ensure
* this is done by the time it returns from {@link #finishUpdate()}.
*
* @param container The containing View from which the page will be removed.
* @param position The page position to be removed.
* @param object The same object that was returned by
* {@link #instantiateItem(View, int)}.
*/
@Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView(mListViews.get(position));
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view==(object);
}
/**
* Called when the a change in the shown pages has been completed. At this
* point you must ensure that all of the pages have actually been added or
* removed from the container as appropriate.
* @param container The containing View which is displaying this adapter's
* page views.
*/
@Override
public void finishUpdate(View arg0) {}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void startUpdate(View arg0) {}
}
}
虽然通过修改源码中launcher类也可以实现类似功能,不过比起重写view这种体力活显然这种方法更环保。