Android GridView ViewPager仿美团首页分类实现
程序员文章站
2022-02-14 11:20:59
...
最近公司的项目需要用类似与美团首页的效果、大概思考了一下决定用 GridView ViewPager 的方式来做、然后通过两个Adapter来实现Item的加载和GridView的翻页效果、下面是Demo的效果图
onCreate初始化
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mViewPagerGrid = (ViewPager) findViewById(R.id.vp); //FEATURE_20160216_1:添加仿美团Headerview begin initDatas(); LayoutInflater inflater = LayoutInflater.from(this); //塞GridView至ViewPager中: int pageSize = pageColumn * pageRow; //一共的页数等于 总数/每页数量,并取整。 int pageCount = (int) Math.ceil(mDatas.size() * 1.0 / pageSize); //ViewPager viewpager = new ViewPager(this); mViewPagerGridList = new ArrayList<View>(); for (int index = 0; index < pageCount; index ) { //每个页面都是inflate出一个新实例 GridView grid = (GridView) inflater.inflate(R.layout.item_viewpager, mViewPagerGrid, false); grid.setAdapter(new GridViewAdapter(this, mDatas, index)); mViewPagerGridList.add(grid); } //FEATURE_20160216_1:添加仿美团Headerview end mViewPagerGrid.setAdapter(new MyViewPagerAdapter(mViewPagerGridList)); }
GridViewAdapter代码
@Override public View getView(int position, View convertView, ViewGroup parent) { Log.i("TAG", "position:" position " :" this); ViewHolder vh = null; if (convertView == null) { convertView = mLayoutInflater.inflate(R.layout.item_gridview_header, parent, false); vh = new ViewHolder(); vh.tv = (TextView) convertView.findViewById(R.id.textView); vh.iv = (ImageView) convertView.findViewById(R.id.imageView); convertView.setTag(vh); } else { vh = (ViewHolder) convertView.getTag(); } /** * 在给View绑定显示的数据时,计算正确的position = position mIndex * mPageSize, */ int pos = position mIndex * mPageSize; vh.tv.setText(mDatas.get(pos).name); vh.iv.setImageResource(mDatas.get(pos).iconRes); return convertView; }
android 仿美团首页分类源代码下载链接: android 仿美团分类 密码: egn2