English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Android Using ViewPager+Implementation of Pagination Effect in Home Navigation Bar Layout with GridView

Recently, I have tried using ViewPager+The GridView is implemented, everything looks normal, no more words, the specific code is as follows:

As shown in the figure is the effect diagram

 

Let's analyze the idea first

1Firstly, let's see how the layout is designed: the whole layout is a ViewPager with a GridView added as a View to the ViewPager's adapter, and below there are circular dots

<?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.The next part is used as the item layout file for ViewPager's GridView (if the outermost layout is RelativeLayout or linear layout, etc., it may cause an exception)

<?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>

3is the writing of the GridView adapter, mainly paying attention to the number if there are all=10data, with a maximum of max=8If there are all=8the second one is2all-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;
/**
 * Adapter for loading data into a GridView
 * @author Administrator
 *
 */
public class MyGridViewAdapter extends BaseAdapter{
  private Context context;
  private List<ProdctBean> lists;//Data source
  private int mIndex; // The page number index, indicating which page it is, starting from 0.
  private int mPargerSize;// Maximum number of items displayed per page
  public MyGridViewAdpter(Context context, List<ProdctBean> lists,
      int mIndex, int mPargerSize) {
    this.context = context;
    this.lists = lists;
    this.mIndex = mIndex;
    this.mPargerSize = mPargerSize;
  }
  /**
   * Firstly, judge whether the size of the data can fill the current page lists.size() > (mIndex + 1)*mPagerSize
   * If the condition is met, display the maximum number of items in the current page, which is the number of items in lists.
   * If the number of items is less than the maximum number to display per page, display the remaining items.
   */
  @Override
  public int getCount() {
    // TODO Auto-generated method stub
    return lists.size() > (mIndex + 1) * mPargerSize &63; 
        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);
    }
      holder = (ViewHolder)convertView.getTag();
    }
    //Re-determine position because the data source is always obtained, and the data source is loaded to each page's GridView in a paginated manner
    final int pos = position + mIndex * mPargerSize;//Assuming mPageSiez
    //Assuming mPagerSize=8, if you click on the second page (i.e., mIndex=1) at the second position item(position=1), then the actual position of this item is pos=9
    holder.tv_name.setText(lists.get(pos).getName() + "
    holder.iv_nul.setImageResource(lists.get(pos).getUrl());
    //Add item listener
//    convertView.setOnClickListener(new View.OnClickListener() {
//      
//      @Override
//      public void onClick(View arg0) {
//        // TODO Auto-generated method stub
//        Toast.makeText(context, "You clicked" + lists.get(pos).getName(), Toast.LENGTH_SHORT).show();
//      }
//    });
    return convertView;
  }
  static class ViewHolder{
    private TextView tv_name;
    private ImageView iv_nul;
  }
}

4. Click event of GridView is provided here2There are two methods: one is to handle the click event of the layout in the adapter; the other is to handle it with Object obj = gridView.getItemAtPosition(position);

5. The main program adds a GridView as a View to the ViewPager, the code is as follows

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;
/**
 * Implement the page effect of the layout of the navigation bar on the home page of Meituan 
 * @author Administrator
 *
 */
public class MyActivity extends Activity {
  private ViewPager viewPager;
  private LinearLayout group;//Dot indicator
  private ImageView[] ivPoints;//Collection of small dot images
  private int totalPage; //Total number of pages
  private int mPageSize = 8; //Maximum number of items displayed per page
  private List<ProdctBean> listDatas;//Total data source
  private List<View> viewPagerList;//Add a GridView as a View object to the ViewPager collection
  //private int currentPage;//Current page
  private String[] proName = {"Name0","Name"1", "Name"2", "Name"3", "Name"4", "Name"5",
      "Name"6", "Name"7", "Name"8", "Name"9", "Name"10", "Name"11", "Name"12", "Name"13",
      "Name"14", "Name"15", "Name"16", "Name"17", "Name"18", "Name"19"};
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    //Initialize controls
    initView();
    //Add business logic
    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
    //Total number of pages is rounded up
    totalPage = (int) Math.ceil(listDatas.size() * 1.0 / mPageSize);
    viewPagerList = new ArrayList<View>();
    for(int i = 0; i < totalPage; i++){
      //Each page is inflated to create a new instance
      final GridView gridView = (GridView)View.inflate(this, R.layout.item_gridview, null);
      gridView.setAdapter(new MyGridViewAdpter(this, listDatas, i, mPageSize));
      //Add item click listener
      gridView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<63;> 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();
          }
        }
      });
      //Each GridView is added as a View object to the ViewPager collection      
      viewPagerList.add(gridView);
    }
    //Set the ViewPager adapter
    viewPager.setAdapter(new MyViewPagerAdapter(viewPagerList));
    //Add small round dots
    ivPoints = new ImageView[totalPage];
    for(int i = 0; i < totalPage; i++){
      //Loop to add dot images to the group
      ivPoints[i] = new ImageView(this);
      if(i==0){
        ivPoints[i].setImageResource(R.drawable.page_focuese);
      }
        ivPoints[i].setImageResource(R.drawable.page_unfocused);
      }
      ivPoints[i].setPadding(8, 8, 8, 8);
      group.addView(ivPoints[i]);
    }
    //Set the scroll listener for ViewPager, mainly to change the background color of the dots
    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);
          }
            ivPoints[i].setImageResource(R.drawable.page_unfocused);
          }
        }
      }
    });
  }
}

6Code for .ViewPage adapter

package com.item.jiejie.adapter;
import java.util.List;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
/**
 * Adapter for ViewPage
 * @author Administrator
 *
 */
public class MyViewPagerAdapter extends PagerAdapter{
  private List<View> viewList;//View is equivalent to a GridView
  public MyViewPagerAdapter(List<View> viewList) {
    this.viewList = viewList;
  }
  @Override
  public int getCount() {
    // TODO Auto-generated method stub
    return viewList!=null63; viewList.size() : 0;
  }
  @Override
  public boolean isViewFromObject(View arg0, Object arg1) {
    // TODO Auto-generated method stub
    return arg0 == arg1;
  }
  /**
   * Add the current View to the ViewGroup container
   * This method returns an object, indicating which object the PagerAdapter adapter selects to be placed on the current 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);
  }
}

That's all for this article. I hope it will be helpful to everyone's learning and also hope everyone will support the Yelling Tutorial more.

Declaration: The content of this article is from the Internet, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal responsibility. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report violations, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like