| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
oracle_java_zxh
8年前发布

Android 仿美团网,探索使用ViewPager+GridView实现左右滑动查看更多分类的功能

   <p>不记得什么时候,我留意到到美团网首页有使用ViewPager+GridView实现左右滑动查看更多分类的一个功能,感觉它很有趣,于是想着自己动手也实现这样一个功能,和往常一样,主要是想总结一下我在学习过程中的一些笔记以及需要注意的地方。</p>    <p>其中需要注意的有如下几个点:</p>    <p>一:使用GridView作为每个ViewPager的页面,也就是说每个ViewPager的页面都是inflate出一个GridView新实例</p>    <p>二:如何将GridView和ViewPager关联起来:在刚刚第一点所说的,有多少个ViewPager的页面就会inflate出多少个GridView作为每页的VIew加入集合中,并将这个集合作为ViewPager的数据源传给ViewPager的Adapter</p>    <pre>  <code class="language-java">//总的页数=总数/每页数量,并取整          pageCount = (int) Math.ceil(mDatas.size() * 1.0 / pageSize);          mPagerList = new ArrayList<View>();          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();                  }              });          }</code></pre>    <p>三:在ViewPager翻页时,如何让GridView显示正确的数据:</p>    <p>(1)给GridView设置Adapter时,除了需要传入总数据集mDatas之外,还需要传入当前页数以及每一页显示的个数,然后经过计算得出正确的count和应该显示的View的数据</p>    <p>(2)在GridView中Adapter中修改getCount()方法:</p>    <pre>  <code class="language-java">/**       * 先判断数据集的大小是否足够显示满本页,如果够,则直接返回每一页显示的最大条目个数pageSize,如果不够,则有几项就返回几,(也就是最后一页的时候就显示剩余item)       */      @Override      public int getCount() {          return mDatas.size() > (curIndex + 1) * pageSize ? pageSize : (mDatas.size() - curIndex * pageSize);        }</code></pre>    <p>(3)修改getView()方法:</p>    <p>在给View绑定显示的数据时,根据当前下标curIndex和每页显示最大数pageSize ,计算一下正确的position = position + curIndex * pageSize</p>    <pre>  <code class="language-java">@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;      }</code></pre>    <p>(4)修改getItem()和getItemId()方法</p>    <pre>  <code class="language-java">@Override      public Object getItem(int position) {          return mDatas.get(position + curIndex * pageSize);      }        @Override      public long getItemId(int position) {          return position + curIndex * pageSize;      }</code></pre>    <p>四、如何在ViewPager翻页时,正确显示目前选中的是那一页呢,也就是说在左右滑动时,下面小圆点的状态也要相应地做出改变:</p>    <pre>  <code class="language-java">/**       * 设置圆点       */      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) {              }          });      }</code></pre>    <p>五、在初始化数据源时,如何动态获取资源ID:</p>    <pre>  <code class="language-java">/**       * 初始化数据源       */      private void initDatas() {          mDatas = new ArrayList<Model>();          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));          }      }</code></pre>    <p>就这五点吧,现在我们先来看看美团网首页使用ViewPager+GridView实现左右滑动查看更多分类的效果图:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/7cdc5992d28c43d888f4215896bc852a.png"></p>    <p style="text-align:center">这里写图片描述</p>    <p>再来看一下我们最终效果图:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/9920b96e5add2289194ae2450deb24ec.gif"></p>    <p style="text-align:center">这里写图片描述</p>    <p>现在我们来看下项目结构图</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/c15665d60f2647a977704e80a3d1fb53.png"></p>    <p style="text-align:center">这里写图片描述</p>    <p>现在我把完整的代码贴出来,由于代码都有注释,下面就不进行一一解释啦</p>    <p>1、MainActivity</p>    <pre>  <code class="language-java">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<View> mPagerList;      private List<Model> 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<View>();          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<Model>();          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) {              }          });      }  }</code></pre>    <p>2、activity_main.xml</p>    <pre>  <code class="language-java"><?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:background="#D4D3D3"      android:orientation="vertical">        <RelativeLayout          android:layout_width="match_parent"          android:layout_height="180dp"          android:background="#FFFFFF">            <android.support.v4.view.ViewPager              android:id="@+id/viewpager"              android:layout_width="match_parent"              android:layout_height="wrap_content" />            <LinearLayout              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" />      </RelativeLayout>  </LinearLayout></code></pre>    <p>分析下布局结构:</p>    <p>(1)首先是一个ViewPager,用于结合GridView实现左右滑动查看更多分类;</p>    <p>(2)下面是一个LinearLayout,有多少个ViewPager的页面就会inflate出多少个小圆点,并且在ViewPager翻页时,也就是说在左右滑动时,下面小圆点的状态也要相应地做出改变</p>    <p>3、GridViewAdapter</p>    <pre>  <code class="language-java">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<Model> mDatas;      private LayoutInflater inflater;      /**       * 页数下标,从0开始(当前是第几页)       */      private int curIndex;      /**       * 每一页显示的个数       */      private int pageSize;        public GridViewAdapter(Context context, List<Model> 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;      }  }</code></pre>    <p>4、ViewPagerAdapter</p>    <pre>  <code class="language-java">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<View> mViewList;        public ViewPagerAdapter(List<View> 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;      }  }</code></pre>    <p>5、Model</p>    <pre>  <code class="language-java">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;      }  }</code></pre>    <p> </p>    <p> </p>    <p>来自:http://www.jianshu.com/p/1bb63a457292</p>    <p> </p>    
 本文由用户 oracle_java_zxh 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1474252794055.html
ViewPager Android开发 移动开发 gridview