Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 利用ViewPager+GridView實現首頁導航欄布局分頁效果

Android 利用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);
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved