A guide to the use of the GridView grid layout in Android apps _android

Source: Internet
Author: User
Tags reflection

0, Common Properties
first let's look at some of the common properties of the GridView

The number of columns for the

1.android:numcolumns= "Auto_fit"//gridview is set to Automatic
2.android:columnwidth= "90DP"//width of each column, which is the width of item,
3. Android:stretchmode= "columnWidth"//Zoom and column width size sync
4.android:verticalspacing= "10DP"//two margin between lines
5.android: horizontalspacing= the margin between "10DP"//Two columns
6.android:cachecolorhint= "#00000000"//Remove the default black background when dragging
7.android: Listselector= "#00000000"///Remove yellow color When selected
8.android:scrollbars= "None"//Hide the GridView scroll bar
9.android: Fadescrollbars= "true"//set to True to automatically hide the scroll bars and display the
10.android:fastscrollenabled= "true"//gridview a fast-scrolling button appears ( Scroll at least 4 pages to display)
11.android:fadingedge= "None"//gridview the fading edge color is empty and the default value is vertical. (can be interpreted as a hint color for the top and bottom edges)
12.android:fadingedgelength= 10DIP//defined decline (fade) edge length
13.android:stackfrombottom= "true"//set to True Your list will show you the bottom of the list
14.android:transcriptmode= "Alwaysscroll"///When you dynamically add data, the list will automatically scroll down the latest entries can automatically scroll to the visual range
15. Android:drawselectorontop= "false"//click on a record, the color will be the background color after the record, the text of the content is visible (default is False)

As for the use of the GridView is not much to say, and ListView usage. The following small series to play and share some of the GridView some of the more special situation.

One, the GridView button picture clicks the effect

We first look at the GridView button Picture Click Effect, not to say that each item click the background color change, that very simple implementation, custom a selector can be realized, the next small series to say is each item on the ImageView click Effect ....
To implement this functionality we want to set ImageView's android:clickable= "true" and look at the layout file:

<imageview android:id= "@+id/itemimage" 
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 color method to change the button picture in the custom adapter, by initializing the adapter, the nine Sudoku pictures are passed over, the color value is changed by the Ontouch event.

Public View.ontouchlistener Ontouchlistener = new View.ontouchlistener () {@Override public boolean Ontouch View View, motionevent event) {switch (event.getaction ()) {Case MotionEvent.ACTION_UP:changeLight (I


          
          Mageview) 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 the GridView picture **/private void Changelight (ImageView imageview, int brightness) {ColorMatrix matrix = n
    EW ColorMatrix (); 
    Matrix.set (New float[] {1, 0, 0, 0, brightness, 0, 1, 0, 0, brightness, 0, 0, 1, 0, brightness, 0, 0, 0, 1, 0}); Imageview.setcolorfilter (New ColormatrixcolorfIlter (matrix));

 }

3. We also need to define an interface to implement the Onitem click event of the GridView

Public interface oncustomitemclicklistener{Public
  int getpostion ();
  public void oncustomitemclk (int i);
  }
  Holder.itemImage.setOnTouchListener (Ontouchlistener);
    Holder.itemImage.setOnClickListener (New View.onclicklistener () {
      @Override public
      void OnClick (view view) {
        clickpos = i;
        LISTENER.ONCUSTOMITEMCLK (Clickpos);
      }
    );

General ideas and the main code are introduced to the very detailed, the need for small partners to download the source code ....

Two, the GridView nine Sudoku Dividing line effect realization (imitation Alipay)

The recent project to implement a copy of the Treasure Nine Sudoku split Line function, because the project is more urgent to find on the Internet, found that are set some background to achieve, leisure time to think, you can customize a GridView to achieve, the following small series to share the implementation method

Set the background to achieve the nine Sudoku split line effect:

Define selector background

<?xml version= "1.0" encoding= "Utf-8"?> <selector xmlns:android= "http://schemas.android.com/apk/res/" Android "></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>

 

To set the layout of the background on it, a little flaw is that each line overlap the line will not overlap the coarse, not seriously see out, but also can make use of, but small series more pursuit of perfection, the following look at the custom GridView implementation method bar.

Three, custom GridView implementation:

Ideas:

1. Get the number of columns of the GridView by reflection

2. Obtaining the Childview of the GridView

3. Draw the line according to Childview

Code:

@Override protected void Dispatchdraw (Canvas Canvas) {super.dispatchdraw (Canvas) int column = 1 try
      {//Get the number of columns by reflection field field = GridView.class.getDeclaredField ("Mnumcolumns") field.setaccessible (True) Column = Field.getint (This)} catch (Nosuchfieldexception e) {e.printstacktrace ()} catch (I  Llegalaccessexception e) {e.printstacktrace ()} int childcount = Getchildcount () Paint Paint = new
    Paint () Paint.setstyle (Paint.Style.STROKE) Paint.setcolor (GetContext (). Getresources (). GetColor (R.color.line)) for (int i = 0 {View Cellview = Getchildat (i) log.e (">>>>>>>>>>>>&gt ;>> "," i= "+i+" | | | | |

      + "Top" +cellview.gettop () + "Bottom" +cellview.getbottom () + ' left ' +cellview.getleft () + "right" +cellview.getright ()) if (Cellview.gettop ()!=0) {//top line, coordinates +1 is to draw on the Cellview Canvas.drawline (Cellview.getleft (), Cellview.gettop () + 1, cellview.getright (), cellview.gettop () + 1, Paint)}//Left line Canvas.drawline (Cellview.getleft () + 1 , Cellview.gettop (), Cellview.getleft () + 1, Cellview.getbottom (), Paint) if ((i + 1)% column = = 0)//rightmost column of cell painting Right line {canvas.drawline (Cellview.getright (), cellview.gettop () + 1, cellview.getright (), Cellview.getbottom () + 1, Paint)} if ((i + column) >= childcount)//Last column cells draw the bottom edge {canvas.drawline Cellview. GetLeft (), Cellview.getbottom () + 1, cellview.getright (), Cellview.getbottom () + 1, Paint)} if (ChildCount% Column!= 0 && i = childCount-1)//If the last cell is not in the right column, draw the right side of the line {Canvas.drawline (cellview.getright () + 1, cellview.gettop () + 1, cellview.getright () + 1, Cellview.getbottom () + 1, paint) canvas.drawline (cellview.

 GetRight () +1, Cellview.getbottom () + 1, cellview.getleft (), Cellview.getbottom () + 1, Paint)}}

Four, to each line to add a split line

Presumably the idea is: since there is no set in the GridView method, it is added directly in the item, in the way of other methods to change the display of the item, so as to set the method of dividing the line ~ nonsense not to say ~ The following detailed introduction: First of all, the GridView layout, Android: Numcolumns= "3″ three columns per line

<gridview
    android:id= "@+id/content"
    android:layout_width= "Fill_parent"
    Match_parent "
    android:numcolumns=" 3 ">
</GridView>

Next is the layout of the item

<?xml version= "1.0" encoding= "UTF-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "android:orientation=" vertical " > <framelayout android:id= "@+id/layout" android:layout_width= "Fill_parent" android:layout_height= "105

    DP "android:layout_marginbottom=" 13DP "android:layout_margintop=" 13DP "android:orientation=" vertical "> <imageview android:id= "@+id/imageview" android:layout_width= "fill_parent" android:layout_height= "10 5DP "android:scaletype=" Centercrop "/> <relativelayout android:layout_width=" Fill_parent "and roid:layout_height= "40DP" android:layout_gravity= "Bottom" android:background= "#50000000" > <textv Iew android:id= "@+id/textview" android:layout_width= wrap_content "android:layout_height=" Wrap_con Tent "Android:layout_centerinpArent= "true" android:gravity= "center" android:maxlines= "2" android:paddingleft= "10DP" Andr oid:paddingright= "10DP" android:textcolor= "@color/text_color" android:textsize= "16sp"/> </relat ivelayout> </FrameLayout> <view android:id= "@+id/line" android:layout_width= "Fill_parent" and

 roid:layout_height= "1px" android:background= "@color/line_color"/> </LinearLayout>

The next most important data is displayed, customizing a gridviewadapter inheritance

public class Gridviewadapter extends Baseadapter {private Layoutinflater inflater;
  private context;

  Private list<map<string, object>> List = new arraylist<map<string, object>> ();
    Public Gridviewadapter (context, list<map<string, object>> List) {super ();
    This.context = context;
    This.list = list;
  Inflater = Layoutinflater.from (context);
  @Override public int GetCount () {return list.size ();
  @Override public Object getitem (int position) {return list.get (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 = inflater.inflate (R.layout.gridview_item, NULL);
      Viewholder = new Viewholder (Convertview);
    Convertview.settag (Viewholder); else {Viewholder = (viewholder) Convertview.gettag ();
    } viewholder.update (List.get (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) Convertview.findviewbyid (R.id.imageview);
      textview= (TextView) Convertview.findviewbyid (R.id.textview);
      layout= (framelayout) Convertview.findviewbyid (r.id.layout);
    View=convertview.findviewbyid (R.id.line); } public void Update (map<string, object> map,int position) {Textview.settext (Map.get ("name"). ToString ())
      ;
      int i=0;
      i=position%3;
        switch (i) {case 0://The first item in each column does not include the layout right inner margin of the split line layout.setpadding (0, 0, 20, 0);
      Break
        Case 1://The second item in each column does not include the layout left and right inner margin of the split line layout.setpadding (10, 0, 10, 0);
      Break Case 2://The third item in each column does not include the split line layout leftInner margin 20; the width of three item must be consistent layout.setpadding (20, 0, 0, 0);
      Break
      Default:break;
      String id=map.get ("id"). toString ();
      SetImage (ID, ImageView);
    Setline (position, view); }} private void SetImage (String id,imageview imageview) {if (Id.equals ("1")) {Imageview.setimageresource (R).
    DRAWABLE.IMG1);
    }else if (Id.equals ("2")) {Imageview.setimageresource (R.DRAWABLE.IMG2);
    }else if (Id.equals ("3")) {Imageview.setimageresource (R.DRAWABLE.IMG3);
    }else if (Id.equals ("4")) {Imageview.setimageresource (R.DRAWABLE.IMG4);
    }else if (Id.equals ("5")) {Imageview.setimageresource (R.DRAWABLE.IMG5);
    } private void Setline (int position,view View) {int i=0;
    I=list.size ()%3;
    if (Position+i+1>list.size ()) {//last line split line hides view.setvisibility (View.gone);
 }
  }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.