您的位置:首页 > 其它

使用ViewPager和GridView配合,实现GridView横向水平滑动的效果。

2013-05-02 16:42 791 查看
实现的原理其实很简单,就是利用Viewpager加入静态的GridView,GridView是写死的。
首先要引入android-support-v4.jar这个包,这个包是用来支持ViewPager这个组件的。

然后在主类的Oncreate方法里:
LayoutInflater mInflater = getLayoutInflater();

//LayoutInflater可以将一个xml布局文件转化为View 类型

View view_01 = mInflater.inflate(R.layout.layout1, null);

View view_02 = mInflater.inflate(R.layout.layout2, null);
private List<View> mViewList = new ArrayList<View>();// 存放待滑动的view
mViewList.clear();//清空老的pager内容后 再加入新的。
mViewList.add(view_01);
mViewList.add(view_02);

GridView gridview = (GridView) view_01.findViewById(R.id.gridview);
GridView gridview2 = (GridView) view_02.findViewById(R.id.gridview2);
(通过上边的方法获取到GridView的插件,然后通过自定义的方法定义一下GridView即可,不会的同学可以先去实现GridView,然后再加上我写的这些代码就可以了)
ViewPager mViewPager = (ViewPager) findViewById(R.id.viewPager);
mViewPager.setAdapter(new MyPagerAdapter());
mViewPager.setCurrentItem(0);// 设置当前pager

再加入一个内部类 也是ViewPager的适配器
class MyPagerAdapter extends PagerAdapter {// 这个是ViewPager的自定义适配器。

@Override
public int getCount() {// 返回view数量
return mViewList.size();
}

@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(mViewList.get(position));
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(mViewList.get(position), 0);
return mViewList.get(position);
}

}


Layout布局文件:




主布局文件中 在对应位置加入这些代码就可以了。

<android.support.v4.view.ViewPager
android:layout_marginLeft="3dip"
android:layout_marginTop="3dip"
android:layout_marginBottom="3dip"
android:layout_marginRight="3dip"
android:id="@+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1" >
</android.support.v4.view.ViewPager>
然后就是两个GridView自己的布局文件,这里只贴出layout1.xml的布局内容,layout2的就不贴了。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"

android:gravity="center" >
<GridView
android:id="@+id/gridview" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:numColumns="5"
android:verticalSpacing="5dp" android:horizontalSpacing="5dp"
android:columnWidth="5dp" android:stretchMode="columnWidth"
android:gravity="center"
>
</GridView>
</LinearLayout>
效果图不能贴因为这个应用不能随便放截图出来,具体效果就想成可以横向滑动的分页GridView(废话),适合我这种 需求固定的 图标固定的应用,动态展示的话需要再这个基础上进行修改。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: