SoFunction
Updated on 2025-04-09

GridView grid layout usage guide in Android App

Zero, Common properties
First, let’s take a look at some commonly used properties of GridView

:numColumns="auto_fit" //The number of columns of GridView is set to automatic
:columnWidth=”90dp” //The width of each column, that is, the width of the Item
:stretchMode="columnWidth" //Scaling is synchronized with column width
:verticalSpacing=”10dp” //The margin between two lines
:horizontalSpacing=”10dp” //The margin between two columns
:cacheColorHint=”#0000000” //Remove the default black background when dragging
:listSelector=”#0000000” //Remove the selected yellow background
:scrollbars="none" //Hide the scrollbar of the GridView
:fadeScrollbars="true" // Set to true to automatically hide and display the scrollbar
:fastScrollEnabled=”true” // A quick scroll button appears in GridView (it will be displayed only after scrolling for at least 4 pages)
:fadingEdge="none" //GridView fades (fading) the edge color is empty, the default value is vertical. (It can be understood as the prompt color of the upper and lower edges)
:fadingEdgeLength=”10dip” //Definition of the length of the fading (fading) edge
:stackFromBottom=”true” // When set to true, the list you made will display the bottom of your list
:transscriptMode="alwaysScroll" //When you add data dynamically, the list will automatically scroll down. The latest entry can be automatically scrolled into the visual range.
:drawSelectorOnTop=”false” //Click on a record and the color will become the background color behind the record, and the text of the content can be visible (default is false)

1. GridView button image click effect

Let’s first look at the click effect of the GridView button image. It does not mean the change of the background color of each item. It is very simple to implement it. Customize a selector. Next, the editor will talk about the click effect of the imageview on each item...
To implement this function, we need to set the imageview android:clickable=”true” and look at the layout file:

<imageview android: 
android:layout_height="50dp" 
android:layout_width="50dp" 
android:scaletype="fitXY" 
android:adjustviewbounds="true" 
android:clickable="true" 
android:layout_margintop="@dimen/smaller_space" 
android:layout_centerhorizontal="true">
</imageview>

2. Then we define a method to change the color of the button image in the custom adapter. When initializing the adapter, we pass the nine-grid image over and change the color value through the onTouch event.

public  onTouchListener = new () {
    @Override
    public boolean onTouch(View view, MotionEvent event) {
      switch (()) {
        case MotionEvent.ACTION_UP:
          changeLight((ImageView) view, 0);


          
          break;
        case MotionEvent.ACTION_DOWN:
          changeLight((ImageView) view, -80);
          break;
        case MotionEvent.ACTION_MOVE:
          
          break;
        case MotionEvent.ACTION_CANCEL:
          changeLight((ImageView) view, 0);
          break;
        default:
          changeLight((ImageView) view, 0);
          break;
      }
      return false;
    }

  };

  /**
   *Change the color value of gridview image
   **/
  private void changeLight(ImageView imageview, int brightness) {
    ColorMatrix matrix = new ColorMatrix();
    (new float[] { 1, 0, 0, 0, brightness, 0, 1, 0, 0,
        brightness, 0, 0, 1, 0, brightness, 0, 0, 0, 1, 0 });
    (new ColorMatrixColorFilter(matrix));

  }

3. We also need to define an interface to implement gridview onItem click event

public interface OnCustomItemClickListener{
  public int getPostion();
  public void onCustomItemClk(int i);
  }
  (onTouchListener);
    (new () {
      @Override
      public void onClick(View view) {
        clickPos = i;
        (clickPos);
      }
    });

The general idea and main code have been introduced to you in detail. If you need it, you can download the source code...

2. Realization of the effect of the nine-grid dividing line of GridView (imitation of Alipay)

Set the background to achieve the effect of nine grid dividing lines:

Define the selector background

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:andro></selector>

  <item android:state_pressed="true"></item><shape android:shape="rectangle"></shape>
    <stroke android:width="1.0px" android:color="@color/line"></stroke>

    <gradient android:angle="270.0" android:endcolor="#ffe8ecef" android:startcolor="#ffe8ecef"></gradient>
  
  <item android:state_focused="true"></item><shape android:shape="rectangle"></shape>
    <gradient android:angle="270.0" android:endcolor="#ffe8ecef" android:startcolor="#ffe8ecef"></gradient>

    <stroke android:width="1.0px" android:color="@color/line"></stroke>
  
  <item></item><shape android:shape="rectangle"></shape>
    <gradient android:angle="270.0" android:endcolor="@color/gray" android:startcolor="@color/gray"></gradient>

    <stroke android:width="0.5px" android:color="@color/line"></stroke>

3. Custom GridView implementation:

Ideas:

1. Get the number of columns of GridView through reflection

2. Get the childview of GridView

3. Draw lines according to the situation of childrenview

Code:

@Override
  protected void dispatchDraw(Canvas canvas)
  {
    (canvas)

    int column = 1
    try
    {
      //Get the column count through reflection      Field field = ("mNumColumns")
      (true)
      column = (this)
    }
    catch (NoSuchFieldException e)
    {
      ()
    }
    catch (IllegalAccessException e)
    {
      ()
    }

    int childCount = getChildCount()
    Paint paint = new Paint()
    ()
    (getContext().getResources().getColor())
    for (int i = 0
    {
      View cellView = getChildAt(i)
      ("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;","i="+i+"||||||||||"+"top"+()+"bottom"+()+"left"+()+"right"+())

      if (()!=0){
        //The top line, coordinate +1 is to be drawn on the cellView        ((), () + 1, (), () + 1, paint)
      }

      //Left line      (() + 1, (), () + 1, (), paint)

      if ((i + 1) % column == 0)   //Draw the right line on the cell on the far right column      {
        ((), () + 1, (), () + 1, paint)
      }
      if ((i + column) &gt;= childCount) //Draw the bottom edge of the column cells at the end      {
        ((), () + 1, (), () + 1, paint)
      }
      if (childCount % column != 0 &amp;&amp; i == childCount - 1)  //If the last cell is not in the rightmost column, draw the right line for it separately      {
        (() + 1, () + 1, () + 1, () + 1, paint)
        (()+1, () + 1, (), () + 1, paint)
      }
    }
  }

4. Add a split line to each line

The general idea is: Since there is no method set in the GridView, it is added directly to the item, and then the display effect of the item is changed through other methods to achieve the method of setting the dividing line~ I won't say much nonsense~ The following detailed introduction: First of all, the layout of the GridView, android:numColumns="3" Three columns per row

<GridView
    android:
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:numColumns="3" >
</GridView>

Next is the layout of the item

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:andro
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical" >

  <FrameLayout
    android:
    android:layout_width="fill_parent"
    android:layout_height="105dp"
    android:layout_marginBottom="13dp"
    android:layout_marginTop="13dp"
    android:orientation="vertical" >

    <ImageView
      android:
      android:layout_width="fill_parent"
      android:layout_height="105dp"
      android:scaleType="centerCrop" />

    <RelativeLayout
      android:layout_width="fill_parent"
      android:layout_height="40dp"
      android:layout_gravity="bottom"
      android:background="#50000000" >

      <TextView
        android:
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:maxLines="2"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:textColor="@color/text_color"
        android:textSize="16sp" />
    </RelativeLayout>
  </FrameLayout>

  <View
    android:
    android:layout_width="fill_parent"
    android:layout_height="1px"
    android:background="@color/line_color" />

</LinearLayout>

Next is the most important data showing, customizing a GridViewAdapter inheritance

public class GridViewAdapter extends BaseAdapter {
  private LayoutInflater inflater;
  private Context context;
  private List&lt;Map&lt;String, Object&gt;&gt; list = new ArrayList&lt;Map&lt;String, Object&gt;&gt;();

  public GridViewAdapter(Context context, List&lt;Map&lt;String, Object&gt;&gt; list) {
    super();
     = context;
     = list;
    inflater = (context);
  }

  @Override
  public int getCount() {
    return ();
  }

  @Override
  public Object getItem(int position) {
    return (position);
  }

  @Override
  public long getItemId(int position) {
    return position;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup arg2) {
    Viewholder viewholder = null;
    if (convertView == null) {
      convertView = (.gridview_item, null);
      viewholder = new Viewholder(convertView);
      (viewholder);
    } else {
      viewholder = (Viewholder) ();
    }
    ((position),position);
    return convertView;
  }

  public class Viewholder {
    private ImageView imageView;
    private TextView textView;
    private FrameLayout layout;
    private View view;
    public Viewholder(View convertView) {
      imageView=(ImageView) ();
      textView=(TextView) ();
      layout=(FrameLayout) ();
      view=();
    }

    public void update(Map&lt;String, Object&gt; map,int position) {
      (("name").toString());
      int i=0;
      i=position%3;
      switch (i) {
      case 0:
        //The first item of each column does not include the layout right inner margin of the dividing line 20        (0, 0, 20, 0);
        break;
      case 1:
        //The second item of each column does not include the layout of the dividing line's layout and the left and right inner margins of 10 each.        (10, 0, 10, 0);
        break;
      case 2:
        //The third item in each column does not include the layout left inner margin of the dividing line 20; the widths of the three items must be consistent        (20, 0, 0, 0);
        break;
      default:
        break;
      }
      String id=("id").toString();
      setImage(id, imageView);
      setLine(position, view);
    }
  }

  private void setImage(String id,ImageView imageView){
    if(("1")){
      (.img1);
    }else if(("2")){
      (.img2);
    }else if(("3")){
      (.img3);
    }else if(("4")){
      (.img4);
    }else if(("5")){
      (.img5);
    }
  }

  private void setLine(int position,View view){
    int i=0;
    i=()%3;
    if(position+i+1&gt;()){
      //The last line of dividing line is hidden      ();
    }
  }