Beginner Android 2016 (10) -- GridView
Like ListView, GridView is a multi-control layout. It is the most convenient to implement the jiugong diagram.
Let's take a look at the picture first. If no picture shows a chicken or chicken, isn't it?
For example, it is an application method. Put the app icon in each grid, and display the app name below.
Next let's take a look at the layout file:
Activity_hello_world.xml
Now let's talk about some new attributes:
Here, dp-related knowledge can be found at Android length.
Android: numColumns = "auto_fit" is set to automatically adapt to the screen width. Only three
Android: verticalSpacing = "10dp" the distance between the two lines is 10 pixels.
Android: horizontalSpacing = "10dp" the distance between the two columns is 10 pixels.
Android: columnWidth = "90dp" width of each column
Android: stretchMode = "columnWidth" scaling and synchronization of column width
Android: gravity = "center" the center is displayed
Let's take a look at the Code:
HelloWorldActivity. java
Package com. fable. helloworld; import android. app. activity; import android. OS. bundle; import android. widget. gridView; import android. widget. simpleAdapter; import java. util. *; public class HelloWorldActivity extends Activity {@ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_hello_world); // you can specify the primary layout file: GridView (gridview) findViewById (R. id. gridview); // create the data source ArrayList
> Images = new ArrayList
> (); For (int I = 1; I <10; I ++) {HashMap
Map = new HashMap
(); Map. put ("ItemImage", R. drawable. ic_launcher); // Add the ID, identifier, and value map of the image resource. put ("ItemText", "application" + String. valueOf (I); // ItemText, identifier, value images by serial number. add (map);} // import data to the adapter and convert it to the data SimpleAdapter simpleAdapter = new SimpleAdapter (this, // The context is the current Activity images, // data source R. layout. my_list_item, // XML implementation of each item Layout new String [] {"ItemImage", "ItemText "}, // The subitem new int [] {R. id. itemImage, R. id. itemText}); // an ImageView in the XML file of ImageItem, two TextView IDs // Add and display the gridview. setAdapter (simpleAdapter );}}
SimpleAdapter can be used here in the same way as ListView. For the usage of SimpleAdapter in ListView, see here.
In fact, the process is very simple, that is, to convert the source data to the adapter data, and then set the adapter to the gridView.
Like ListView, each item requires a layout file.
My_list_item.xml
Here, ItemText is set under ItemImage, and both are vertically centered.