Part 88: ViewPager aka Homescreen fling/swipe.
If you want the kind of swipe or fling you get on the homescreen, you need to use the ViewPager element. This is in the compatibility pack, if you’re not using 3.0.
You can download this in the Android SDK and ADK manager. If you may already have it. If not, check the available and installed tabs and download it.
Then, in Eclipse, load that by going to Project -> Properties -> Java Build Path -> Libraries tab.
Then click the Add External Jar. Then navigate to the android-sdk/extras/android/compatibility/v4 directory and click on the ‘android-support-v4.jar’.
This code is from http://code.google.com/p/viewpagerexample/ from Paul G.
Now the simple XML code. Note ViewPager’s required full XML name:
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”>
<android.support.v4.view.ViewPager
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/viewpager”/>
</LinearLayout>
Now we need to fill that ViewPager with data. We do that with an adapter. Set it up in your onCreate method:
adapter = new MyPagerAdapter();
pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(adapter);
Now the MyPagerAdapter class. This extends the PagerAdapter for the ViewPager.
private class MyPagerAdapter extends PagerAdapter{
@Override
public int getCount() {
return 3;
}
@Override
public Object instantiateItem(View collection, int position) {
TextView tv = new TextView(getApplicationContext());
tv.setText(“Hallo”);
((ViewPager) collection).addView(tv,0);
return tv;
}
@Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((TextView) view);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view==((TextView)object);
}
@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) { }
}
All these methods are required. But to get it up and running, you only need to define a few.
You only need to say how many items you have in getCount(), remove the old View in destroyItem(), which is passed the container, position and old View. And isViewFromObject is undocumented.
Note all the references to the TextView in the methods above will change if you’re returning something other than a TextView.
Finally, instantiateItem(). This is passed the ViewPager and the position it’s currently at. From this you must return the View you want to display. And add it to the passed collection, i.e Viewpager.
Also, this ViewPager takes up all the screen, from what I can tell. Or at least nothing can be placed below it—above it is okay.