Android 0 Basics Section 45th: GridView Simple to use

Source: Internet
Author: User

The previous 8 period to learn the ListView list of related operations, in fact, the knowledge of the ListView is fully applicable to adapterview other subclasses, such as the GridView, Spinner, Autocompletetextview and other components, Then the next step to learn about these list components, this issue first learn the use of the GridView.

First, to know the GridView

The ListView in front is a list, where the GridView is the display grid, which is used to display multiple components in the interface by row and column distribution.

The GridView and ListView have a common parent class: Abslistview, so the GridView and ListView have very high similarities, both of which are list items. The only difference between the GridView and the ListView is that the ListView displays only one column, while the GridView can display multiple columns. From this point of view, the ListView is equivalent to a special GridView, if the GridView only display a column, then the GridView becomes a ListView. Similar to the ListView, the GridView also needs to provide the displayed data through adapter: Developers can create adapter using either of the several methods described above. In either case, the use of the GridView and the ListView is basically consistent.

The common XML attributes provided by the GridView and related methods are shown in the following table.

The Android:stretchmode property in the table above supports several property values.

    • No_stretch: Do not stretch.

    • Stretch_spacing: Stretches only the spacing between elements.

    • Stretch_spacing_uniform: The table element itself and the spacing between elements are stretched together.

    • Stretch_column_width: Stretches only the table element itself.

It is also important to note that when using the GridView you should generally specify that NumColumns is greater than 1, otherwise the default value for this property is 1. If this property is set to 1, it means that the GridView has only one column, then the GridView becomes a ListView.

Second, the GridView example

Next, learn how to use the GridView using a simple example program.

Continue to use the Listviewsample module of the Widgetsample project to create a gridview_layout.xml file in the app/main/res/layout/directory populated with the following code snippet:

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"android:orientation= "vertical"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:gravity= "Center_horizontal">    <!--Define a GridView component -    <GridViewAndroid:id= "@+id/gridview"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"android:horizontalspacing= "1DP"android:verticalspacing= "1DP"Android:numcolumns= "4"android:gravity= "Center"/></LinearLayout>

Android:numcolumns= "4" was specified when the GridView was defined, which means that the grid contains 4 columns. The GridView contains rows that are dynamically changed-just as the ListView contains exactly how many rows are determined by the adapter of the ListView, and how many rows the GridView contains are also determined by adapter.

Create a new Gridview_item.xml list item layout file under the res/layout/directory with the following code:

<?XML version= "1.0" encoding= "UTF-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:gravity= "Center_horizontal"android:orientation= "vertical"android:padding= "5DP" >    <ImageViewAndroid:id= "@+id/icon_img"Android:layout_width= "48DP"Android:layout_height= "48DP" />    <TextViewAndroid:id= "@+id/name_tv"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_margintop= "5DP"/></LinearLayout>

Next for the GridView to provide adapter, the implementation of a variety of ways, here use Simpleadapter decide what the GridView to display. Create a new Gridviewactivity.java file and load the new layout file above, with the following code:

 Packagecom.jinyu.cqkxzsxy.android.listviewsample;ImportAndroid.os.Bundle;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.view.View;ImportAndroid.widget.AdapterView;ImportAndroid.widget.GridView;ImportAndroid.widget.SimpleAdapter;ImportAndroid.widget.Toast;Importjava.util.ArrayList;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map; Public classGridviewactivityextendsappcompatactivity {PrivateGridView Mappgridview =NULL; //app icon    Private int[] Mappicons ={r.drawable.app_1, r.drawable.app_2, R.drawable.app_3, R.drawable.app_4, R.drawable.app_5, R.D    Rawable.app_6, R.drawable.app_7, R.drawable.app_8, r.drawable.app_9}; //Application Name    Privatestring[] Mappnames = {            "Magic wand", "like community", "Shopping street", "Ant community", "Xin 鱻 map",            "Xin 鱻 News", "Room goods sink", "mall", "model Box"    }; @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (r.layout.gridview_layout); //Get interface ComponentsMappgridview =(GridView) Findviewbyid (R.id.gridview); //initializes the data, creates a list object, and the element of the list object is the maplist<map<string, object>> listItems =NewArraylist<map<string, object>>();  for(inti = 0; i < mappicons.length; i++) {Map<string, object> ListItem =NewHashmap<string, object>(); Listitem.put ("Icon", Mappicons[i]); Listitem.put ("Name", Mappnames[i]);        Listitems.add (ListItem); }        //Create a SimpleadapterSimpleadapter Simpleadapter =NewSimpleadapter ( This, ListItems, R.layout.gridview_item,Newstring[]{"icon", "name"},                New int[]{r.id.icon_img, R.ID.NAME_TV}]; //set adapter for the GridViewMappgridview.setadapter (Simpleadapter); //add list item clicked ListenerMappgridview.setonitemclicklistener (NewAdapterview.onitemclicklistener () {@Override Public voidOnitemclick (adapterview<?> Parent, view view,intPositionLongID) {//show the picture you clickedToast.maketext (gridviewactivity. This, Mappnames[position], Toast.length_short). Show ();    }        }); }}

The above program also uses the Simpleadapter object as the adapter of the GridView, which guarantees a 9-length list collection, which means that the gridview-altogether needs to display 9 components, There are a total of 4 columns in the GridView, so the gridview-contains 3 rows altogether.

Modify the program startup activity, run the program, you can see the interface effect shown on the left.

Click the icon in the interface to see the message prompt, as shown on the right.

At this point, the GridView simple use of learning is complete, more properties and methods are recommended to practice and master.

Come here today, if you have any questions welcome message to discuss together, also welcome to join the Android 0 Basic introductory Technical discussion group, grow together!

This article copyright for the public Share talent show (Shareexpert)--Xin 鱻 all, if necessary reprint please contact the author authorized, hereby declare!

Past period Summary share:

Android 0 Basics Introduction 1th: Android's past life

Android 0 Basics Section 2nd: Android system Architecture and application components those things

Android 0 Basics Section 3rd: Bring you up to talk about Android development environment

Android 0 Basics 4th: Installing and configuring the JDK correctly Ko fu the first trick

Android 0 Basics 5th: Use ADT bundles to easily meet the goddess

Android 0 Basics 6th: Configuration Optimization SDK Manager, official dating goddess

Android 0 Basics 7th: Take care of Android simulator and start the Sweet journey

Android 0 Basics 8th: HelloWorld, the starting point for my first trip

Android 0 Basics 9th: Android app, no code can be developed

Android 0 Basics Section 10th: Development IDE Big upgrade, finally ushered in Android Studio

Android 0 Basics Introductory Section 11th: Simple steps to take you to fly, run Android Studio project

Android 0 Basics 12th: Get familiar with the Android studio interface and start selling

Android 0 Basics 13th: Android Studio Configuration optimization to create a development tool

Android 0 Basics 14th: Using high-speed genymotion, stepping into the rocket era

Android 0 Basics Section 15th: Mastering the Android Studio project structure, sailing

Android 0 Basics Section 16th: Android User Interface Development overview

Android 0 Basics Section 17th: TextView Properties and Methods Daquan

Android 0 Basics Section 18th: EditText properties and how to use them

Android 0 Basics section 19th: Button usage explained

Android 0 Basics Section 20th: checkbox and RadioButton Usage Daquan

Android 0 Basics Section 21st: ToggleButton and switch usage Daquan

Android 0 Basics Section 22nd: ImageView's properties and methods Daquan

Android 0 Basics Section 23rd: ImageButton and Zoombutton use Daquan

Android 0 Basics Section 24th: Customize view simple to use to create your own controls

Android 0 Basics Section 25th: Simple and most commonly used linearlayout linear layouts

Android 0 Basics Section 26th: Two alignments, layout_gravity and gravity differ greatly

Android 0 Basics section 27th: Using padding and margin correctly

Android 0 Basics Section 28th: Easy to master relativelayout relative layout

Android 0 Basics 29th: Use tablelayout table layouts

Android 0 Basics 30th: Two minutes master Framelayout frame layout

Android 0 Basics Section 31st: absolutelayout absolute Layout with less

Android 0 Basics Section 32nd: New GridLayout Grid layout

Android 0 Basics section 33rd: Android Event Handling overview

Android 0 Basics Section 34th: Listening-based event handling in Android

Android 0 Basics Section 35th: Callback-based event handling in Android

Android 0 Basics Section 36th: Handling of Android system events

Android 0 Basics 37th: First Knowledge ListView

Android 0 Basics 38th: First Knowledge Adapter

Android 0 Basics section 39th: listactivity and custom list items

Android 0 Basics Section 40th: Customizing Arrayadapter

Android 0 Basics Section 41st: Using Simpleadapter

Android 0 Basics Section 42nd: Customizing Baseadapter

Android 0 Basics section 43rd: ListView Optimization and List End-to-end use

Android 0 Basics Section 44th: ListView Data Dynamic Update

Android 0 Basics Section 45th: GridView Simple to use

Related Article

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.