实现步骤
1 布局文件添加 android.support.v4.view.ViewPager确定区域
<android.support.v4.view.ViewPager
android:id="@+id/main_viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_gravity="center"
android:persistentDrawingCache="animation" />
2 创建ViewPager mViewPager对象
mViewPager = (ViewPager)findViewById(R.id.main_viewPager);
3 创建HashMap<String, Object> map容器
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("ItemImage", R.drawable.main_btn_radio);// 添加图像资源的ID
map.put("ItemText", getString(R.string.Radio).toString());// 按序号做ItemText
4 创建ArrayList<HashMap<String, Object>> lstImageItem
把HashMap对象添加到ArrayList中 ,即lstImageItem.add(map);
如果是八宫格需添加八个HashMap对象到ArrayList中,如此类推!
5 创建SimpleAdapter saImageItems对象
SimpleAdapter saImageItems = new SimpleAdapter(this,
lstImageItem,// 数据列表
R.layout.item,// 每个宫格的布局
new String[] { "ItemImage", "ItemText" },// 动态数组与ImageItem对应的子项
new int[] { R.id.item_imageButton1, R.id.item_textView1 });// ImageItem的XML文件里面的一个ImageView,一个TextView ID
6 创建GridView gridview对象,把saImageItems 设置为gridview的接口
gridview.setAdapter(saImageItems);
gridview.setNumColumns(4);
gridview.setOnItemClickListener(this);
gridview.setOnTouchListener(this);
7 创建ArrayList<View> mViewList对象,把gridview添加到ArrayList<View>中
ArrayList<View> mViewList = new ArrayList<View>();
mViewList.add(gridview); //此时是一页的数据
8 创建PagerAdapter mPagerAdapter对象,把ArrayList<View>的数据给PagerAdapter调用
//ViewPager适配器
mPagerAdapter = new PagerAdapter() {
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
@Override
public int getCount() {
return mViewList.size();
}
@Override
public void destroyItem(View container, int position, Object object) {
((ViewPager)container).removeView(mViewList.get(position));
}
@Override
public Object instantiateItem(View container, int position) {
((ViewPager)container).addView(mViewList.get(position));
return mViewList.get(position);
}
};
9 把PagerAdapter设置为ViewPager 的接口
mViewPager.setAdapter(mPagerAdapter);
注意:PagerAdapter作为ViewPager的适配器接口时
页面初始化后需调用notifyDataSetChanged();通知数据改变!
mPagerAdapter.notifyDataSetChanged();
过程:(至上而下)
ViewPage--PagerAdapter--ArrayList<View>--gridview--SimpleAdapter--ArrayList<HashMap<String, Object>>--HashMap<String, Object>