不记得什么时候,我留意到到美团网首页有使用ViewPager+GridView实现左右滑动查看更多分类的一个功能,感觉它很有趣,于是想着自己动手也实现这样一个功能,和往常一样,主要是想总结一下我在学习过程中的一些笔记以及需要注意的地方。此文章已经同步到CSDN啦,欢迎访问我的博客
其中需要注意的有如下几个点:
一:使用GridView作为每个ViewPager的页面,也就是说每个ViewPager的页面都是inflate出一个GridView新实例
二:如何将GridView和ViewPager关联起来:在刚刚第一点所说的,有多少个ViewPager的页面就会inflate出多少个GridView作为每页的VIew加入集合中,并将这个集合作为ViewPager的数据源传给ViewPager的Adapter
//总的页数=总数/每页数量,并取整
pageCount = (int) Math.ceil(mDatas.size() * 1.0 / pageSize);
mPagerList = new ArrayList();
for (int i = 0; i < pageCount; i++) {
// 每个页面都是inflate出一个新实例
GridView gridView = (GridView) inflater.inflate(R.layout.gridview, mPager, false);
gridView.setAdapter(new GridViewAdapter(this, mDatas, i, pageSize));
mPagerList.add(gridView);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
int pos = position + curIndex * pageSize;
Toast.makeText(MainActivity.this, mDatas.get(pos).getName(), Toast.LENGTH_SHORT).show();
}
});
}
三:在ViewPager翻页时,如何让GridView显示正确的数据:
(1)给GridView设置Adapter时,除了需要传入总数据集mDatas之外,还需要传入当前页数以及每一页显示的个数,然后经过计算得出正确的count和应该显示的View的数据
(2)在GridView中Adapter中修改getCount()方法:
/**
* 先判断数据集的大小是否足够显示满本页,如果够,则直接返回每一页显示的最大条目个数pageSize,如果不够,则有几项就返回几,(也就是最后一页的时候就显示剩余item)
*/
@Override
public int getCount() {
return mDatas.size() > (curIndex + 1) * pageSize ? pageSize : (mDatas.size() - curIndex * pageSize);
}
(3)修改getView()方法:
在给View绑定显示的数据时,根据当前下标curIndex和每页显示最大数pageSize ,计算一下正确的position = position + curIndex * pageSize
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_gridview, parent, false);
viewHolder = new ViewHolder();
viewHolder.tv = (TextView) convertView.findViewById(R.id.textView);
viewHolder.iv = (ImageView) convertView.findViewById(R.id.imageView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
/**
* 在给View绑定显示的数据时,计算正确的position = position + curIndex * pageSize
*/
int pos = position + curIndex * pageSize;
viewHolder.tv.setText(mDatas.get(pos).name);
viewHolder.iv.setImageResource(mDatas.get(pos).iconRes);
return convertView;
}
(4)修改getItem()和getItemId()方法
@Override
public Object getItem(int position) {
return mDatas.get(position + curIndex * pageSize);
}
@Override
public long getItemId(int position) {
return position + curIndex * pageSize;
}
四、如何在ViewPager翻页时,正确显示目前选中的是那一页呢,也就是说在左右滑动时,下面小圆点的状态也要相应地做出改变:
/**
* 设置圆点
*/
public void setOvalLayout() {
for (int i = 0; i < pageCount; i++) {
mLlDot.addView(inflater.inflate(R.layout.dot, null));
}
// 默认显示第一页
mLlDot.getChildAt(0).findViewById(R.id.v_dot)
.setBackgroundResource(R.drawable.dot_selected);
mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageSelected(int position) {
// 取消圆点选中
mLlDot.getChildAt(curIndex)
.findViewById(R.id.v_dot)
.setBackgroundResource(R.drawable.dot_normal);
// 圆点选中
mLlDot.getChildAt(position)
.findViewById(R.id.v_dot)
.setBackgroundResource(R.drawable.dot_selected);
curIndex = position;
}
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
public void onPageScrollStateChanged(int arg0) {
}
});
}
五、在初始化数据源时,如何动态获取资源ID:
/**
* 初始化数据源
*/
private void initDatas() {
mDatas = new ArrayList();
for (int i = 0; i < titles.length; i++) {
//动态获取资源ID,第一个参数是资源名,第二个参数是资源类型例如drawable,string等,第三个参数包名
int imageId = getResources().getIdentifier("ic_category_" + i, "mipmap", getPackageName());
mDatas.add(new Model(titles[i], imageId));
}
}
就这五点吧,现在我们先来看看美团网首页使用ViewPager+GridView实现左右滑动查看更多分类的效果图:
这里写图片描述
再来看一下我们最终效果图:
这里写图片描述
现在我们来看下项目结构图
这里写图片描述
现在我把完整的代码贴出来,由于代码都有注释,下面就不进行一一解释啦
1、MainActivity
package per.lijuan.meituan;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private String[] titles = {"美食", "电影", "酒店住宿", "休闲娱乐", "外卖", "自助餐", "KTV", "机票/火车票", "周边游", "美甲美睫",
"火锅", "生日蛋糕", "甜品饮品", "水上乐园", "汽车服务", "美发", "丽人", "景点", "足疗按摩", "运动健身", "健身", "超市", "买菜",
"今日新单", "小吃快餐", "面膜", "洗浴/汗蒸", "母婴亲子", "生活服务", "婚纱摄影", "学习培训", "家装", "结婚", "全部分配"};
private ViewPager mPager;
private List mPagerList;
private List mDatas;
private LinearLayout mLlDot;
private LayoutInflater inflater;
/**
* 总的页数
*/
private int pageCount;
/**
* 每一页显示的个数
*/
private int pageSize = 10;
/**
* 当前显示的是第几页
*/
private int curIndex = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPager = (ViewPager) findViewById(R.id.viewpager);
mLlDot = (LinearLayout) findViewById(R.id.ll_dot);
//初始化数据源
initDatas();
inflater = LayoutInflater.from(this);
//总的页数=总数/每页数量,并取整
pageCount = (int) Math.ceil(mDatas.size() * 1.0 / pageSize);
mPagerList = new ArrayList();
for (int i = 0; i < pageCount; i++) {
// 每个页面都是inflate出一个新实例
GridView gridView = (GridView) inflater.inflate(R.layout.gridview, mPager, false);
gridView.setAdapter(new GridViewAdapter(this, mDatas, i, pageSize));
mPagerList.add(gridView);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
int pos = position + curIndex * pageSize;
Toast.makeText(MainActivity.this, mDatas.get(pos).getName(), Toast.LENGTH_SHORT).show();
}
});
}
//设置适配器
mPager.setAdapter(new ViewPagerAdapter(mPagerList));
//设置圆点
setOvalLayout();
}
/**
* 初始化数据源
*/
private void initDatas() {
mDatas = new ArrayList();
for (int i = 0; i < titles.length; i++) {
//动态获取资源ID,第一个参数是资源名,第二个参数是资源类型例如drawable,string等,第三个参数包名
int imageId = getResources().getIdentifier("ic_category_" + i, "mipmap", getPackageName());
mDatas.add(new Model(titles[i], imageId));
}
}
/**
* 设置圆点
*/
public void setOvalLayout() {
for (int i = 0; i < pageCount; i++) {
mLlDot.addView(inflater.inflate(R.layout.dot, null));
}
// 默认显示第一页
mLlDot.getChildAt(0).findViewById(R.id.v_dot)
.setBackgroundResource(R.drawable.dot_selected);
mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageSelected(int position) {
// 取消圆点选中
mLlDot.getChildAt(curIndex)
.findViewById(R.id.v_dot)
.setBackgroundResource(R.drawable.dot_normal);
// 圆点选中
mLlDot.getChildAt(position)
.findViewById(R.id.v_dot)
.setBackgroundResource(R.drawable.dot_selected);
curIndex = position;
}
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
public void onPageScrollStateChanged(int arg0) {
}
});
}
}
2、activity_main.xml
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#D4D3D3"
android:orientation="vertical">
android:layout_width="match_parent"
android:layout_height="180dp"
android:background="#FFFFFF">
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
android:id="@+id/ll_dot"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="8dp"
android:gravity="center"
android:orientation="horizontal" />
分析下布局结构:
(1)首先是一个ViewPager,用于结合GridView实现左右滑动查看更多分类;
(2)下面是一个LinearLayout,有多少个ViewPager的页面就会inflate出多少个小圆点,并且在ViewPager翻页时,也就是说在左右滑动时,下面小圆点的状态也要相应地做出改变
3、GridViewAdapter
package per.lijuan.meituan;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
/**
* Created by lijuan on 2016/9/12.
*/
public class GridViewAdapter extends BaseAdapter {
private List mDatas;
private LayoutInflater inflater;
/**
* 页数下标,从0开始(当前是第几页)
*/
private int curIndex;
/**
* 每一页显示的个数
*/
private int pageSize;
public GridViewAdapter(Context context, List mDatas, int curIndex, int pageSize) {
inflater = LayoutInflater.from(context);
this.mDatas = mDatas;
this.curIndex = curIndex;
this.pageSize = pageSize;
}
/**
* 先判断数据集的大小是否足够显示满本页,如果够,则直接返回每一页显示的最大条目个数pageSize,如果不够,则有几项就返回几,(也就是最后一页的时候就显示剩余item)
*/
@Override
public int getCount() {
return mDatas.size() > (curIndex + 1) * pageSize ? pageSize : (mDatas.size() - curIndex * pageSize);
}
@Override
public Object getItem(int position) {
return mDatas.get(position + curIndex * pageSize);
}
@Override
public long getItemId(int position) {
return position + curIndex * pageSize;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_gridview, parent, false);
viewHolder = new ViewHolder();
viewHolder.tv = (TextView) convertView.findViewById(R.id.textView);
viewHolder.iv = (ImageView) convertView.findViewById(R.id.imageView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
/**
* 在给View绑定显示的数据时,计算正确的position = position + curIndex * pageSize
*/
int pos = position + curIndex * pageSize;
viewHolder.tv.setText(mDatas.get(pos).name);
viewHolder.iv.setImageResource(mDatas.get(pos).iconRes);
return convertView;
}
class ViewHolder {
public TextView tv;
public ImageView iv;
}
}
4、ViewPagerAdapter
package per.lijuan.meituan;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
/**
* Created by lijuan on 2016/9/12.
*/
public class ViewPagerAdapter extends PagerAdapter {
private List mViewList;
public ViewPagerAdapter(List mViewList) {
this.mViewList = mViewList;
}
@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));
return (mViewList.get(position));
}
@Override
public int getCount() {
if (mViewList == null)
return 0;
return mViewList.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
5、Model
package per.lijuan.meituan;
/**
* Created by lijuan on 2016/9/12.
*/
public class Model {
public String name;
public int iconRes;
public Model(String name, int iconRes) {
this.name = name;
this.iconRes = iconRes;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIconRes() {
return iconRes;
}
public void setIconRes(int iconRes) {
this.iconRes = iconRes;
}
}
好了,本篇文章已经全部写完了,有什么疑问的,请在下面留言,存在总结不到位的地方还望指导,感谢_