欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 利用ViewPager+GridView实现首页导航栏布局分页效果

程序员文章站 2024-03-02 21:07:40
最近我尝试使用viewpager+gridview实现的,看起来一切正常,废话不多说,具体代码如下: 如图是效果图   首先分析下思路 1.首...

最近我尝试使用viewpager+gridview实现的,看起来一切正常,废话不多说,具体代码如下:

如图是效果图

 Android 利用ViewPager+GridView实现首页导航栏布局分页效果

首先分析下思路

1.首先是怎么布局:整体是一个viewpager将gridview作为一个view添加到viewpager的adapter中,下方是圆点

<?xml version="1.0" encoding="utf-8"?>
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="#cdcdcd" >

  <relativelayout
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="#fff" >

    <android.support.v4.view.viewpager
      android:id="@+id/viewpager"
      android:layout_width="match_parent"
      android:layout_height="wrap_content" />

    <linearlayout
      android:id="@+id/points"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_alignparentbottom="true"
      android:layout_marginbottom="10dp"
      android:gravity="center"
      android:orientation="horizontal" />
  </relativelayout>

</relativelayout>

2.接下来时作为viewpager的item布局文件gridview,(如果最外层是relativelayout或线型布局等,会转换异常)

<?xml version="1.0" encoding="utf-8"?>
<gridview xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/gridview"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:numcolumns="4">

</gridview>

3.是gridview适配器的编写,主要是注意数量如果一共有all=10条数据,每页最多max=8条的话,第一个页面就是个数是max=8,第二个就2个all-max

package com.item.jiejie.adapter;

import java.util.list;

import com.item.jiejie.prodctbean;
import com.item.jiejie.r;
import android.content.context;
import android.view.view;
import android.view.viewgroup;
import android.widget.baseadapter;
import android.widget.imageview;
import android.widget.textview;
import android.widget.toast;

/**
 * gridview加载数据的适配器
 * @author administrator
 *
 */
public class mygridviewadpter extends baseadapter{
  
  private context context;
  private list<prodctbean> lists;//数据源
  private int mindex; // 页数下标,标示第几页,从0开始
  private int mpargersize;// 每页显示的最大的数量
  
  
  
  public mygridviewadpter(context context, list<prodctbean> lists,
      int mindex, int mpargersize) {
    this.context = context;
    this.lists = lists;
    this.mindex = mindex;
    this.mpargersize = mpargersize;
  }

  /**
   * 先判断数据及的大小是否显示满本页lists.size() > (mindex + 1)*mpagersize
   * 如果满足,则此页就显示最大数量lists的个数
   * 如果不够显示每页的最大数量,那么剩下几个就显示几个
   */
  @override
  public int getcount() {
    // todo auto-generated method stub
    return lists.size() > (mindex + 1) * mpargersize ? 
        mpargersize : (lists.size() - mindex*mpargersize);
  }

  @override
  public prodctbean getitem(int arg0) {
    // todo auto-generated method stub
    return lists.get(arg0 + mindex * mpargersize);
  }

  @override
  public long getitemid(int arg0) {
    // todo auto-generated method stub
    return arg0 + mindex * mpargersize;
  }

  @override
  public view getview(int position, view convertview, viewgroup parent) {
    // todo auto-generated method stub
    viewholder holder = null;
    if(convertview == null){
      holder = new viewholder();
      convertview = view.inflate(context, r.layout.item_view, null);
      holder.tv_name = (textview)convertview.findviewbyid(r.id.item_name);
      holder.iv_nul = (imageview)convertview.findviewbyid(r.id.item_image);
      convertview.settag(holder);
    }else {
      holder = (viewholder)convertview.gettag();
    }
    //重新确定position因为拿到的总是数据源,数据源是分页加载到每页的gridview上的
    final int pos = position + mindex * mpargersize;//假设mpagesiez
    //假设mpagersize=8,假如点击的是第二页(即mindex=1)上的第二个位置item(position=1),那么这个item的实际位置就是pos=9
    holder.tv_name.settext(lists.get(pos).getname() + "");
    holder.iv_nul.setimageresource(lists.get(pos).geturl());
    //添加item监听
//    convertview.setonclicklistener(new view.onclicklistener() {
//      
//      @override
//      public void onclick(view arg0) {
//        // todo auto-generated method stub
//        toast.maketext(context, "您点击了" + lists.get(pos).getname(), toast.length_short).show();
//      }
//    });
    return convertview;
  }
  static class viewholder{
    private textview tv_name;
    private imageview iv_nul;
  }
}

4.gridview的点击事件这里提供2种方法一种是在适配器用布局的点击事件来处理;第二种是object obj = gridview.getitematposition(position);来处理。

5.主程序将gridview作为view添加到viewpager中 代码如下

package com.item.jiejie;

import java.util.arraylist;
import java.util.list;
import com.item.jiejie.adapter.mygridviewadpter;
import com.item.jiejie.adapter.myviewpageradapter;
import android.app.activity;
import android.os.bundle;
import android.support.v4.view.viewpager;
import android.view.view;
import android.widget.adapterview;
import android.widget.adapterview.onitemclicklistener;
import android.widget.gridview;
import android.widget.imageview;
import android.widget.linearlayout;
import android.widget.toast;

/**
 * 实现仿美团首页导航栏布局分页效果 
 * @author administrator
 *
 */
public class myactivity extends activity {
  private viewpager viewpager;
  private linearlayout group;//圆点指示器
  private imageview[] ivpoints;//小圆点图片的集合
  private int totalpage; //总的页数
  private int mpagesize = 8; //每页显示的最大的数量
  private list<prodctbean> listdatas;//总的数据源
  private list<view> viewpagerlist;//gridview作为一个view对象添加到viewpager集合中
  //private int currentpage;//当前页
  
  private string[] proname = {"名称0","名称1","名称2","名称3","名称4","名称5",
      "名称6","名称7","名称8","名称9","名称10","名称11","名称12","名称13",
      "名称14","名称15","名称16","名称17","名称18","名称19"};
  @override
  protected void oncreate(bundle savedinstancestate) {
    // todo auto-generated method stub
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_my);
    //初始化控件
    initview();
    //添加业务逻辑
    initdata();
  }
  
  private void initview() {
    // todo auto-generated method stub
    viewpager = (viewpager)findviewbyid(r.id.viewpager);
    group = (linearlayout)findviewbyid(r.id.points);
    listdatas = new arraylist<prodctbean>();
    for(int i =0 ; i < proname.length; i++){
      listdatas.add(new prodctbean(proname[i], r.drawable.iv_driving));
    }
  }
  private void initdata() {
    // todo auto-generated method stub
    //总的页数向上取整
    totalpage = (int) math.ceil(listdatas.size() * 1.0 / mpagesize);
    viewpagerlist = new arraylist<view>();
    for(int i = 0; i < totalpage; i++){
      //每个页面都是inflate出一个新实例
      final gridview gridview = (gridview)view.inflate(this, r.layout.item_gridview, null);
      gridview.setadapter(new mygridviewadpter(this, listdatas, i, mpagesize));
      //添加item点击监听
      gridview.setonitemclicklistener(new onitemclicklistener() {

        @override
        public void onitemclick(adapterview<?> arg0, view arg1,
            int position, long arg3) {
          // todo auto-generated method stub
          object obj = gridview.getitematposition(position);
          if(obj != null && obj instanceof prodctbean){
            system.out.println(obj);
            toast.maketext(myactivity.this, ((prodctbean)obj).getname(), toast.length_short).show();
          }
        }
      });
      //每一个gridview作为一个view对象添加到viewpager集合中      
      viewpagerlist.add(gridview);
    }
    //设置viewpager适配器
    viewpager.setadapter(new myviewpageradapter(viewpagerlist));
    
    //添加小圆点
    ivpoints = new imageview[totalpage];
    for(int i = 0; i < totalpage; i++){
      //循坏加入点点图片组
      ivpoints[i] = new imageview(this);
      if(i==0){
        ivpoints[i].setimageresource(r.drawable.page_focuese);
      }else {
        ivpoints[i].setimageresource(r.drawable.page_unfocused);
      }
      ivpoints[i].setpadding(8, 8, 8, 8);
      group.addview(ivpoints[i]);
    }
    //设置viewpager的滑动监听,主要是设置点点的背景颜色的改变
    viewpager.setonpagechangelistener(new viewpager.simpleonpagechangelistener(){
      @override
      public void onpageselected(int position) {
        // todo auto-generated method stub
        //currentpage = position;
        for(int i=0 ; i < totalpage; i++){
          if(i == position){
            ivpoints[i].setimageresource(r.drawable.page_focuese);
          }else {
            ivpoints[i].setimageresource(r.drawable.page_unfocused);
          }
        }
      }
    });
  }
}

6.viewpage的适配器代码

package com.item.jiejie.adapter;

import java.util.list;

import android.support.v4.view.pageradapter;
import android.view.view;
import android.view.viewgroup;

/**
 * viewpage的适配器
 * @author administrator
 *
 */
public class myviewpageradapter extends pageradapter{
  
  private list<view> viewlist;//view就二十gridview
  
  
  public myviewpageradapter(list<view> viewlist) {
    this.viewlist = viewlist;
  }

  @override
  public int getcount() {
    // todo auto-generated method stub
    return viewlist!=null ? viewlist.size() : 0;
  }

  @override
  public boolean isviewfromobject(view arg0, object arg1) {
    // todo auto-generated method stub
    return arg0 == arg1;
  }
  /**
   * 将当前的view添加到viewgroup容器中
   * 这个方法,return一个对象,这个对象表明了pageradapter适配器选择哪个对象放在当前的viewpage上
   */
  @override
  public object instantiateitem(viewgroup container, int position) {
    // todo auto-generated method stub
    container.addview(viewlist.get(position));
    return viewlist.get(position);
  }
  
  @override
  public void destroyitem(viewgroup container, int position, object object) {
    // todo auto-generated method stub
     container.removeview((view) object);
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。