Simple use of listview + arrayadapter in Android

Source: Internet
Author: User

Arrayadapter

I always feel that I can learn more only when I write my own blog. Although there are a lot of good information on the Internet, it is uneven and it takes a lot of time to find the most desired information, simply write what you need most.

Adapter means the adapter. In Android, listview is widely used, and listview can be used only by combining with various adapters. Different adapters are used in different scenarios, so the most common ones will be helpful to you in the future.

Arrayadapter (array adapter) is generally used to display a line of text information, so it is easier.

Public arrayadapter (context, int textviewresourceid, list <t> objects)

The above line of code is used to assemble data. to assemble the data, an adapter connecting the listview view object and the array data is required to adapt the two. The arrayadapter structure requires three parameters, this is the layout file (note that the layout file here describes the layout of each row in the list. For details, see main. XML file, android. r. layout. simple_list_item_1 is a layout file defined by the system that only displays one line of text, a data source (a list set ). At the same time, use setadapter () to bind the listview and adapter.

 

Example 1: a text can be simply displayed.

Main. xml

<? 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"> <textview Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: text = "cnblogs -- huarang"/> <listview Android: Id = "@ + ID/listview" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"/> </linearlayout>

Activity

Package COM. loulijun. demo14; import Java. util. arraylist; import android. app. activity; import android. OS. bundle; import android. widget. arrayadapter; import android. widget. listview; public class demo13activity extends activity {private listview lv; private arraylist <string> List = new arraylist <string> (); @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); Lv = (listview) findviewbyid (R. id. listview); arrayadapter <string> adapter = new arrayadapter <string> (this, android. r. layout. simple_expandable_list_item_1, getdata (); LV. setadapter (adapter);} private arraylist <string> getdata () {list. add ("180 square meters house"); list. add ("a hardworking and beautiful wife"); list. add ("a bmw"); list. add ("a strong and never ill"); list. add ("A favorite career"); return list ;}}

Note: Here, Android. R. layout. simple_expandable_list_item_1 is the built-in layout of the system. The style is as follows. You can also customize the layout and import it into the layout, but only one textview can be used.

Very few codes. You can understand them at first glance. Some of the troubles may be caused by generics. If you don't understand them, you can refer to the basics of Java. The running effect is as follows:

Example 2: You can add an imageview in this example, but you need to add this custom layout when setting the arrayadapter.

Public arrayadapter (context, int resource, int textviewresourceid, list <t> objects)

The first parameter above is the context, generally this. The second parameter is a custom Layout file, for example, R. layout. list_item. The third parameter is the ID of textview, and the fourth parameter is data.

List_item.xml (main. XML is the same as above)

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal" >    <ImageView         android:id="@+id/img"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:src="@drawable/ic_launcher"        />    <TextView         android:id="@+id/tv"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        /></LinearLayout>

Activity

Package COM. loulijun. demo14; import Java. util. arraylist; import android. app. activity; import android. OS. bundle; import android. widget. arrayadapter; import android. widget. listview; public class demo13activity extends activity {private listview lv; private arraylist <string> List = new arraylist <string> (); @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); Lv = (listview) findviewbyid (R. id. listview); arrayadapter <string> adapter = new arrayadapter <string> (this, R. layout. list_item, R. id. TV, getdata (); LV. setadapter (adapter);} private arraylist <string> getdata () {list. add ("180 square meters house"); list. add ("a hardworking and beautiful wife"); list. add ("a bmw"); list. add ("a strong and never ill"); list. add ("A favorite career"); return list ;}}

The arrayadapter and simpleadapter are also different here. It needs to set a custom layout in the adapter and then set the textview ID in it. However, it is very difficult to implement other controls, such as setting different graphs.

Baseadapter or simpleadaper is preferred for images with texts. Arrayadapter is suitable for some simple text information.

The effect is as follows:

Example 3: implement complex results

To be honest, this is a tough job to write, a lot of results cannot be achieved, or baseadapter is more omnipotent, but I still want to talk about how to use arrayadapter to implement complicated attempts. This requires rewriting the getview method, similar to baseadapter.

There are many advantages to override the getview method. For example, during listview optimization, operations in this method are mainly optimized. In addition, custom views are basically loaded using this method, to achieve your desired results

 

I want to display all the images in the/dcim/camera directory of the SD card to a list. On the left side of each item in this list is the thumbnail of the image, and on the right side is the file name.

Analysis:

This application is very typical.Data BindingAddCustom display.

How can this problem be solved?

1. Customize the list Style

Image_item.xml

<?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="horizontal"> <ImageView     android:id="@+id/item_thumbnail"     android:layout_height="48dip"     android:layout_width="48dip"         /> <TextView     android:id="@+id/item_file_name"     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:textAppearance="?android:attr/textAppearanceLarge"     android:minHeight="?android:attr/listPreferredItemHeight"     android:gravity="center_vertical"     android:paddingLeft="5dip"     /></LinearLayout>

2. Custom arrayadapter

Imagelistadapter

Public class imagelistadapter extends arrayadapter <File> {private int resource; Public imagelistadapter (context, int resourceid, list <File> objects) {super (context, resourceid, objects ); // record it and use resource = resourceid later;} public view getview (INT position, view convertview, viewgroup parent) {linearlayout imagelistview; // obtain the data file = getitem (position ); string filename = file. getnam E (); Bitmap bitmap = getbitmapfromfile (File); // when the system displays the list, an adapter is first instantiated (the custom adapter will be instantiated here ). // When manual adaptation is completed, data must be manually mapped. You need to override the getview () method. // The system calls this method when drawing each row of the list. // Getview () has three parameters. // position indicates the rows to be displayed. // covertview indicates the inflate layout from the layout file. // We use the layoutinflater method to extract the defined image_item.xml file into a view instance for display. // Instantiate each component in the XML file (simple findviewbyid () method ). // You can map the data to each component. // If (convertview = NULL) {imagelistview = new linearlayout (getcontext ()); // check the definition of layoutinflater In the android document. // This class is used to instantiate layout XML file into its corresponding view objects. // It is never be used directly -- use getlayoutinflater () or getsystemservice (string) // to retrieve a standard layoutinflater instance that is already hooked up to the current // context and correctly configured for the device you are running on .. for example: String Inflater = context. layout_inflater_service; layoutinflater Vi = (layoutinflater) getcontext (). getsystemservice (Inflater); VI. inflate (resource, imagelistview, true); // This log is called every time you select images. D ("adapter", "convertview is null now");} else {// it is strange that imagelistview = (linearlayout) convertview; log has not been called. D ("adapter", "convertview is not null now");} // fill in custom data imageview = (imageview) imagelistview. findviewbyid (R. id. item_thumbnail); textview = (textview) imagelistview. findviewbyid (R. id. item_file_name); textview. settext (filename); imageview. setimagebitmap (Bitmap); Return imagelistview;} // obtain the bitmap from the file to fill in the private bitmap getbitmapfromfile (File file) {Bitmap bitmap = bitmapfactory. decodefile (file. getabsolutepath (); Return bitmap ;}}

3. Bind data

private void bindFilesToList(File[] files) {         List<File> fileList = new ArrayList<File>();         for(File file : files) {             fileList.add(file);         }        ImageListAdapter adapter = new ImageListAdapter(ImageFilesListActivity.this,                                                         R.layout.image_item,                                                         fileList);         setListAdapter(adapter); }

This is basically the case.

 

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.