实现美团宫格导航ViewPager+GridView

原创 2016年05月31日 11:15:01
本人新手,但是对安卓开发情有独钟
          最近在开发一款社区的APP,之前客户有定好需求,但是不知道后面为什么又改了,其中有一个就是要做想美团一样的宫格导航,于是笔者昨晚弄出一个demo,主要用于学习。做出来效果还不错。现在来秀一秀源码。
布局文件:
   activity_main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    	<android.support.v4.view.ViewPager
    	    android:id="@+id/vPager"
    	    android:layout_width="match_parent"
    	    android:layout_height="232dp"
    	    android:background="#ff0000" >
    	</android.support.v4.view.ViewPager>

    	<LinearLayout
    	    android:id="@+id/ll_dots"
    	    android:layout_width="match_parent"
    	    android:layout_height="20dp"
    	    android:layout_marginTop="200dp"
    	    android:gravity="center"
    	    android:orientation="horizontal" >
    	</LinearLayout>

</FrameLayout>
channel_gridview_item.xml:
<?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:gravity="center"
    android:orientation="vertical" >
    
    <!-- ViewPager每页GridView 的Item的布局 -->
    <ImageView 
        android:id="@+id/iv_gv_item_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView 
        android:id="@+id/tv_gv_item_Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:ellipsize="end"/> 
          


</LinearLayout>
channel_viewpage_gridview.xml:
<?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:gravity="center"
    android:orientation="vertical" >
    
   <!-- 每个页面的GridView -->
   <GridView 
       android:id="@+id/vp_gv"
       android:layout_width="match_parent"
       android:layout_height="match_parent" 
       android:horizontalSpacing="10dp"
       android:verticalSpacing="10dp"
       android:gravity="center">
       
   </GridView>
   
        
</LinearLayout>
InfoBean.java:
package com.example.grid_pager;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


import android.graphics.drawable.Drawable;
import android.view.View;

/**
 * 
 * @author Administrator
 * 这是用于显示item的bean,朋友们可以根据自己的需求修改。
 * 
 *
 */
public class InfoBean implements Comparable<InfoBean>{

	private int id;  
    private String name;  
    private Drawable icon;  
    private String iconUrl;  
    private int iconID;  
    private String describtion;  
    private int type;  
    // 排序标记  
    private int order; 
    
    private onGridViewItemClickListener onClickListener; 
	
    
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Drawable getIcon() {
		return icon;
	}
	public void setIcon(Drawable icon) {
		this.icon = icon;
	}
	public String getIconUrl() {
		return iconUrl;
	}
	public void setIconUrl(String iconUrl) {
		this.iconUrl = iconUrl;
	}
	public int getIconID() {
		return iconID;
	}
	public void setIconID(int iconID) {
		this.iconID = iconID;
	}
	public String getDescribtion() {
		return describtion;
	}
	public void setDescribtion(String describtion) {
		this.describtion = describtion;
	}
	public int getType() {
		return type;
	}
	public void setType(int type) {
		this.type = type;
	}
	public int getOrder() {
		return order;
	}
	public void setOrder(int order) {
		this.order = order;
	}
	
	
	
	public InfoBean(String name, int iconID, int order) {
		super();
		this.name = name;
		this.iconID = iconID;
		this.order = order;
	}
	public InfoBean() {
		super();
	}
	
	
	@Override
	public int compareTo(InfoBean another) {
		if (another != null) {  
            if (this.getOrder() > another.getOrder()) {  
                return 1;  
            } else {  
                return -1;  
            }  
        } else {  
            return 0;  
        }  
	}  
	
	  public onGridViewItemClickListener getOnClickListener() {  
	        return onClickListener;  
	    }  
	    public void setOnClickListener(onGridViewItemClickListener onClickListener) {  
	        this.onClickListener = onClickListener;  
	    }
	    
	    //得到排序的List  
	    public static ArrayList<InfoBean> getOrderList(ArrayList<InfoBean> list) {  
	        Collections.sort(list);  
	        return list;  
	    }  
	    
    //item点击监听接口	    
    public interface onGridViewItemClickListener  
		    {  
		        public abstract void ongvItemClickListener(View v);  
		    }
	
	
}


<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">MainActivity.java:</span>
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"></span><pre name="code" class="java">package com.example.grid_pager;

import java.util.ArrayList;

import com.example.grid_pager.adapter.ViewPager_GV_ItemAdapter;
import com.example.grid_pager.adapter.ViewPager_GridView_Adapter;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
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
 *程序步骤:
 *    1.准备要显示的数据
 *    2.加载视图
 *    	2.1加载下面显示页的小圆点
 *      2.2显示小圆点的位置
 *    3.设置ViewPager的Adapter
 *    4.设置每页的GridView的Adapter
 */
public class MainActivity extends Activity {

	//准备数据
	ArrayList<InfoBean> list=null;
	InfoBean info=null;
	ViewPager viewPager;
	LinearLayout ll_dots;
    private ImageView[] dots;  
	  
	/** ViewPager页数 */  
	 private int viewPager_size;
	//当前页
	private int currentIndex;
	//gridView 页面item的数量
	int pageItemCount;
	//页面的宽高
	int width;
	int height;
	//保存每个GridView的视图
	ArrayList<View> viewlist=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		WindowManager wm=(WindowManager)this.getSystemService(this.WINDOW_SERVICE);
		width=wm.getDefaultDisplay().getWidth();
		height=wm.getDefaultDisplay().getHeight();
		Log.e("width", width+"");
		Log.e("height", height+"");
		list=getData();
		Log.e("size", list.size()+"");
		//初始化视图
		initView();
	}
	private void initView() {
        viewPager=(ViewPager) findViewById(R.id.vPager);
        ll_dots=(LinearLayout) findViewById(R.id.ll_dots);
        initDots();
        setAdapter();
	}
	private void setAdapter() {
		viewlist=new ArrayList<View>();
		for(int i=0;i<viewPager_size;i++){
			viewlist.add(getGridViewItem(i));    //36
		}
		viewPager.setAdapter(new ViewPager_GridView_Adapter(viewlist));
	}
	//每个GridView页面中的布局
	private View getGridViewItem(int index) {
		LayoutInflater inflater=(LayoutInflater) this.getSystemService(this.LAYOUT_INFLATER_SERVICE);
		View layout=inflater.inflate(R.layout.channel_viewpage_gridview, null);
		GridView gridView=(GridView) layout.findViewById(R.id.vp_gv);
		
		int col=(width/160) >2 ?(width/160):3;
		
		Log.e("col", col+"");//3   4
		gridView.setNumColumns(col);
		//每个页面的adapter
		ViewPager_GV_ItemAdapter adapter=new ViewPager_GV_ItemAdapter(this, list, index, pageItemCount);
		gridView.setAdapter(adapter);
		//设置gridView中点击Item事件
		gridView.setOnItemClickListener(new OnItemClickListener() {

			

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Toast.makeText(MainActivity.this, position + currentIndex * pageItemCount+"", Toast.LENGTH_SHORT).show();
					if(null !=list.get(position + currentIndex * pageItemCount).getOnClickListener()){
						list.get(position+currentIndex*pageItemCount).getOnClickListener().ongvItemClickListener(view);
					}
			}
		});
		return gridView;
	}
	private void initDots() {
		int col = (width/160) >2 ? (width/160) :3;   //3    4
        int row = (height/400) >4?(height/400):2;   //2     2
        pageItemCount = col * row;  //每一页可装item   //6
        //gridView 的页数
        viewPager_size = list.size() / pageItemCount +1;  //5
  
        if (0 < viewPager_size) {  
            ll_dots.removeAllViews();  
            if (1 == viewPager_size) {  
                ll_dots.setVisibility(View.GONE);  
            } else if (1 < viewPager_size) {  
                ll_dots.setVisibility(View.VISIBLE);  
                for (int j = 0; j < viewPager_size; j++) {  
                    ImageView image = new ImageView(this);  
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(10, 10);  //dot的宽高
                    params.setMargins(3, 0, 3, 0);  
                    image.setBackgroundResource(R.drawable.dot_unselected);  
                    ll_dots.addView(image, params);  
                }  
            }  
        }  
        if (viewPager_size != 1) {  
            dots = new ImageView[viewPager_size];  
            for (int i = 0; i < viewPager_size; i++) {
            	//从布局中填充dots数组
                dots[i] = (ImageView) ll_dots.getChildAt(i);  
                //dots[i].setEnabled(true);  
                //dots[i].setTag(i);  
            }  
            currentIndex = 0;  //当前页
            //dots[currentIndex].setEnabled(false);  
            dots[currentIndex].setBackgroundResource(R.drawable.dot_selected);
            viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {  
  
                @Override  
                public void onPageSelected(int arg0) {  
                    setCurDot(arg0);  
                }  
  
               

				@Override  
                public void onPageScrolled(int arg0, float arg1, int arg2) {  
                    // TODO Auto-generated method stub  
  
                }  
  
                @Override  
                public void onPageScrollStateChanged(int arg0) {  
                    // TODO Auto-generated method stub  
  
                }  
            });  
        }  
		
	}
	private ArrayList<InfoBean> getData() {
		list=new ArrayList<InfoBean>();
		for(int i=0;i<46;i++){
			info=new InfoBean("苹果"+i, R.drawable.apple, i);
			list.add(info);
		}
		return list;
	}
	 private void setCurDot(int position) {
		 if (position < 0 || position > viewPager_size - 1 || currentIndex == position) {  
	            return;  
	        } 
	        for(int i=0;i<dots.length;i++){
	        	dots[i].setBackgroundResource(R.drawable.dot_unselected);
	        }
	        //dots[positon].setEnabled(false);  
	       // dots[currentIndex].setEnabled(true);  
	        dots[position].setBackgroundResource(R.drawable.dot_selected);
	        currentIndex = position;  
			
		}
}



ViewPager_GridView_Adapter.java:
package com.example.grid_pager.adapter;

import java.util.ArrayList;

import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
/**
 * 
 * @author Administrator
 *ViewPager的adapter
 */
public class ViewPager_GridView_Adapter extends PagerAdapter{
	ArrayList<View> viewlist;
	
	public ViewPager_GridView_Adapter(ArrayList<View> viewlist){
		this.viewlist=viewlist;
	}
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return viewlist.size();
	}

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		//return false;
		return arg0==(arg1);
	}
	
	public Object instantiateItem(View arg0, int arg1) {
		try {
		//解决View只能滑动两屏的方法
		ViewGroup parent = (ViewGroup) viewlist.get(arg1).getParent();
		 if (parent != null) {
			 parent.removeAllViews();
		 } 
		//container.addView(v);
		((ViewPager) arg0).addView(viewlist.get(arg1),0);
		} catch (Exception e) {
		e.printStackTrace();
		}

		return viewlist.get(arg1);
		}


		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
		   try {
		    ((ViewPager) arg0).removeView(viewlist.get(arg1));
		} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
		}
		}

}


ViewPager_GV_ItemAdapter.java:
package com.example.grid_pager.adapter;

import java.util.ArrayList;
import java.util.List;

import com.example.grid_pager.InfoBean;
import com.example.grid_pager.R;

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;
/**
 * 
 * @author Administrator
 *每页GridView的adapter
 */
public class ViewPager_GV_ItemAdapter extends BaseAdapter{

	private ArrayList<InfoBean> infolist;  
    private Context context;  
	   /** ViewPager页码 */  
	private int index;  
	    /** 根据屏幕大小计算得到的每页item个数 */  
    private int pageItemCount;  
	    /** 传进来的List的总长度 */  
    private int totalSize;  
	
	public ViewPager_GV_ItemAdapter(Context context,ArrayList<InfoBean> list){
		this.context=context;
		infolist=list;
	}
	
	 public ViewPager_GV_ItemAdapter(Context context, List<?> list, int index, int pageItemCount) {  
	        this.context = context;  
	        this.index = index;  
	        this.pageItemCount = pageItemCount;  
	        infolist = new ArrayList<InfoBean>();  
	        totalSize = list.size();  //36   40
	        // itemRealNum=list.size()-index*pageItemCount;  
	        // 当前页的item对应的实体在List<?>中的其实下标  
	        int list_index = index * pageItemCount;  
	        for (int i = list_index; i < list.size(); i++) {  
	        	infolist.add((InfoBean) list.get(i));  
	        }  
	  
	    } 
	@Override
	public int getCount() {
		int size=totalSize/pageItemCount;
		if(index==size){
			return totalSize-pageItemCount*index;
		}else{
			return pageItemCount;
		}
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return infolist.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
       ViewHoler vh;
       if(convertView==null){
    	   vh=new ViewHoler();
    	   convertView=LayoutInflater.from(context).inflate(R.layout.channel_gridview_item, null);
    	   vh.iv_icon=(ImageView) convertView.findViewById(R.id.iv_gv_item_icon);
    	   vh.tv_mame=(TextView) convertView.findViewById(R.id.tv_gv_item_Name);
    	   convertView.setTag(vh);
       }else{
    	   vh=(ViewHoler) convertView.getTag();
       }
       vh.updateViews(position, null);
		return convertView;
	}
	  class ViewHoler{
      	ImageView iv_icon;
      	TextView tv_mame;
      	public void updateViews(int position, Object inst ){
      		iv_icon.setImageResource(infolist.get(position).getIconID());
      		tv_mame.setText(infolist.get(position).getName());
      	}
      }

}

小弟刚开始学些博客,所以还有很多要学习的地方,刚开始只会罗列代码,所以有需要改进的地方希望大家多多提意见,小弟一定多家改正!!!

相关文章推荐

Viewpager嵌套GridView的实现

最近再做一个相关的项目,网上查了一些关于viewpagerqiant
  • Mkite
  • Mkite
  • 2014年09月04日 14:44
  • 9155

Android ViewPager嵌套GridView实现滚动菜单(demo)

目前国内的app很常见的一种首页菜单布局就是类似于大众点评等团购网站的首页菜单交,如下图上边的菜单区域,通常在Android中是将GridView装填到ViewPager中进行显示,网上的例子或多或少...

Delphi7高级应用开发随书源码

  • 2003年04月30日 00:00
  • 676KB
  • 下载

Android UI开发篇之 ViewPager+九宫格布局 实现左右滑动

首先看下UI效果:                这个是我在业余开发的新浪微博广场模块的一个实现页面左右滑动的效果,用到的有android.support.v4.view.ViewPager 实现...

Delphi7高级应用开发随书源码

  • 2003年04月30日 00:00
  • 676KB
  • 下载

ViewPager+gridView仿美团导航

相信大家都用过美团吧,是不是被它的精美的导航页面给迷住!今天,咱们就实现它那个多页面滑动导航效果,话不多说,先上效果图:                                       ...

Android之ViewPager+GridView实现仿美团首页导航栏布局分页效果

用过美团app的小伙伴都应该非常熟悉,美团首页的分类导航栏是作为一个头布局展示在首页上的,并且分类过多的话则可以滑动查看。本篇博客正如题目所说,采用ViewPager+GridView的方式来实现美团...

Delphi7高级应用开发随书源码

  • 2003年04月30日 00:00
  • 676KB
  • 下载

Delphi7高级应用开发随书源码

  • 2003年04月30日 00:00
  • 676KB
  • 下载

教你如何实现淘宝天猫的首页可以滑动的gridview导航

源码https://github.com/helloworld107/MeituanDemon/new/master?readme=1 效果图 源码分析: 我们应该知道一个不能滑动的列表图标...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:实现美团宫格导航ViewPager+GridView
举报原因:
原因补充:

(最多只允许输入30个字)