2) the code for the src/skynet.com. cnblogs. www/helloworld. Java file is as follows: package skynet.com.cnblogs.www;import android.app.ListActivity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.TextView;import android.widget.Toast;import android.widget.AdapterView.OnItemClickListener;public class HelloWorld extends ListActivity {// Note that the helloworld class is not extended from acitty, but from listacitivty/** called when the activity is first created. * // @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate );Setlistadapter (New arrayadapter <string> (this, R. layout. Main, countries ));Listview Lv = getlistview (); LV. settextfilterenabled (true); LV. setonitemclicklistener (New onitemclicklistener () {public void onitemclick (adapterview <?> Parent, view, int position, long ID) {// when clicked, show a toast with the textview text toast. maketext (getapplicationcontext (), (textview) view ). gettext (), toast. length_short ). show () ;}) ;}static final string [] countries = new string [] {"1", "2", "3", "4 ", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14 ", "15", "16", "17", "18", "19", "20", "21", "22", "23 ", "24 "};}Note: The oncreate () function does not load the layout file for the activity through setcontentview () as usual. InsteadSetlistadapter (listadapter) automatically adds a listactivity that fills the screen with listview. In this file, this method takes an arrayadapter as the parameter:Setlistadapter (New arrayadapter <string> (this, R. layout. Main, countries )), This arrayadapter is managed to fill in the list elements in the listview. The constructor parameters of arrayadapter are: This (indicating the context of the application) and listviewde layout file (R. layout. main), insert the list object to the listview array (countres ). Setonitemclicklistener (onitemclicklistener) defines the on-click listener for each element. When an element in the listview is clicked,The onitemclick () method is called.ToastMessage-the position of each element is displayed.
3) run the application as follows ): Figure 7. List Layout Note:If you change helloworld extendsListactivityInsteadActivityThen, run the program with the prompt "conversion to Dalvik format failed with error 1 ". Solution: Project> clean...> CLEAN project selected below> OK 5.1. A small improvementThe above code is to hard encode the elements to be filled in the listview to the helloworld. Java file, which lacks flexibility! Does not meet the recommendationApplication InterfaceAndCode that controls its behaviorThe principle of better separation! In fact, we can write the elements to be filled in the listviewres/values/strings.xmlFile<string-array>Element, and then dynamically read from the source code. In this way, the content of strings. XML is similar to the following: <?xml version="1.0" encoding="utf-8"?><resources> <string-array name="countries_array"> <item>1</item> <item>2</item> <item>3</item> <item>4</item> <item>5</item> <item>6</item> <item>7</item> </string-array></resources> However, the oncreate () function in the helloworld. Java file dynamically accesses this array and fills in listvies: String [] countries = getresources (). getstringarray (R. array. countries_array ); Setlistadapter (New arrayadapter <string> (this, R. layout. list_item, countries )); 5.2 supplementary instructionsFirst, summarize the key parts of the List layout:
- Define listview in layout File
- The adapter is used to fill data in the listview.
- The data to be filled in the listview can be strings, images, controls, and so on.
The adapter serves as a bridge between listview and the data source. There are three types of adapters based on different data sources:
- String []: arrayadapter
- List <Map <string,?> : Simpleadapter
- Database cursor: simplecursoradapter
Using arrayadapter (array adapter), as its name implies, you need to put data into an array for display. The example above is like this. simpleadapter can define various la S and put imageview (image ), you can also put buttons, checkbox, and so on. simplecursoradapter is related to the database. If the length is limited, the following two methods will not be used as an example. For details about the differences between orarrayadapter, simpleadapter, and simplecursoradapter, see Android listview. 6Grid View)Grid layout: A viewgroup displays its child view elements in a grid, that is, a two-dimensional, scrolling grid. Grid elements pass throughThe listadapter is automatically inserted into the grid.The listadapter has the same layout as the preceding list. The following is an example to create a grid that displays thumbnail images. When an element is selected, a message indicating the position of the element in the list is displayed. 1) first, put the image captured in the previous practiceres/drawable/ 2) the Res/layour/Main. XML content is set to the following: The gridview fills up the entire screen, and its attributes are well understood. It means the English word. <?xml version="1.0" encoding="utf-8"?><GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gridview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:columnWidth="90dp" android:numColumns="auto_fit" android:verticalSpacing="10dp" android:horizontalSpacing="10dp" android:stretchMode="columnWidth" android:gravity="center"/> 3). Then, the oncreate () function in the helloworld. Java file is as follows: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); GridView gridview = (GridView) findViewById(R.id.gridview); gridview.setAdapter(new ImageAdapter(this)); gridview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Toast.makeText(HelloWorld.this, " " + position, Toast.LENGTH_SHORT).show(); } }); } The oncreate () function is the same as the normal one. First, call the oncreate () function of the superclass, and then use setcontentview () to load the layout file for the activity. Then, get the gridview in the layout file through the ID of the gridview, and then call itssetListAdapter(ListAdapter)The function fills it in. Its parameter is a custom imageadapter. The subsequent work is the same as that in the list layout. It listens to the clicked events of elements in the grid. 4) Implement custom imageadapter and add a new class file. Its code is as follows: package skynet.com.cnblogs.www;import android.content.Context;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.GridView;import android.widget.ImageView;public class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context c) { mContext = c; } public int getCount() { return mThumbIds.length; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } // create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // if it's not recycled, initialize some attributes imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(85, 85)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(8, 8, 8, 8); } else { imageView = (ImageView) convertView; } imageView.setImageResource(mThumbIds[position]); return imageView; } // references to our images private Integer[] mThumbIds = { R.drawable.linearlayout1, R.drawable.linearlayout2, R.drawable.linearlayout3, R.drawable.listview, R.drawable.relativelayout, R.drawable.tablelayout };} Imageadapter class extended fromBaseadapter, so you must first implement the required methods. The constructor and getcount () functions are well understood, while getitem (INT) should return the specific location of the actual object in the adapter, but we do not need it here. Similarly, getitemid (INT) should return the row number of the element, but this is not required here. Here we will focus on the getview () method, which creates a new view for each image to be added to the imageadapter. When this method is called, a view is recycled, so check whether the object is empty. If it is null,ImageViewIt is instantiated and configured with the desired display attribute:
setLayoutParams(ViewGroup.LayoutParams): Set the height and width of the view. This ensures that no matter the size of the image in the drawable, the size of each image is reset and cropped to fit the size.
setScaleType(ImageView.ScaleType): Declare that the image should be cropped to the center (if needed ).
setPadding(int, int, int, int): Defines the padding. If the image has different vertical and horizontal ratios, a smaller padding will cause more cropping to fit the height and width of the Set imageview.
If the upload of view to getview () is not empty, the local imageview will be recycled and then used with the view object during initialization. At the end of the getview () method, the position integer is passed into the setimageresource () method to select an image from the mthumbids array. Run the program and you will get the following results (after clicking the first image ): Figure 8 grid layout |