Android Development uses custom Arrayadapter to make ListView items

Source: Internet
Author: User
Tags static class unique id xmlns

Background information

For real-world business mobile applications, Android's ListView default interface looks unattractive. It simply uses the internal TextView control, passing a simple string within each ListView row (row). For most applications, you will want to create a rich graphical interface and present a good application for the user's visual experience. Fortunately, ListView is a very powerful control that can be customized to fit your needs with the help of a customizable item layout. In this article, I'll show you how to create a custom ListView Item (with icons, custom header layouts) and how to use custom Arrayadapter to connect them. I'll also show you some little performance-optimized ways to optimize the memory footprint of your ListView control. Here's an example to show:

Figure 1. Weather Tutu 2. Layout structure diagram
            

I. Layout of the project

In Eclipse, create a new Android project that uses the default activity and Main.xml layout files. In the Main.xml file, declare a ListView control.

Main.xml file:
 1 <?xml version= "1.0" encoding= "Utf-8"
 2 <linearlayout
 3      xmlns:android=http://schemas.android.com/apk/res/android
 4      android:orientation= "vertical"
 5     android:layout_width= "Fill_parent"
 6     android:layout_height= "Fill_parent"
 7     android: background= "#FFFFFF" >
 8    
 9      < ListView
10         android:id= "@+id/listview1"
11          android:layout_width= "Fill_parent"
12          android:layout_height= "Fill_parent"/>
</linearlayout>

The code above, which uses a simple linear layout, is arranged vertically inside. Declares a ListView, occupies the entire parent container, and his android.layout_width and Android.layout_width properties are fill_parent. ListView has a unique id:listview1 that will be used in mainactivity to reference ListView controls.

To create a custom header, first create a new XML layout file in your project: Listview_header_row.xml, declare a TextView control inside, and the attribute value is shown in the following code. A white font with a blue background header will be created.


1 listview_header_row.xml Files:
2 <?xml version= "1.0" encoding= "Utf-8"?>
3 <linearlayout
4 xmlns:android= "Http://schemas.android.com/apk/res/android"
5 android:orientation= "Horizontal"
6 android:layout_width= "Fill_parent"
7 android:layout_height= "Fill_parent" >
8
9 <textview android:id= "@+id/txtheader"
Ten android:layout_width= "Fill_parent"
One android:layout_height= "Fill_parent"
Android:gravity= "Center_vertical"
Android:layout_alignparenttop= "true"
Android:layout_alignparentbottom= "true"
Android:textstyle= "Bold"
Android:textsize= "22DP"
Android:textcolor= "#FFFFFF"
Android:padding= "10DP"
android:text= "Weather Photos"
android:background= "#336699"/>
21st
</LinearLayout>

To create a custom ListView row style, first create another XML layout file in your project: Listview_item_row.xml. Android will pass the contents of this file to each ListView item, and you will be free to declare any controls you want to add to it. In this article, I used a imageview to display the weather icon and a textview to display the item's subject. The following is the code for the Listview_item_row.xml file:


1 listview_item_row.xml Files:
2 <?xml version= "1.0" encoding= "Utf-8"?>
3 <linearlayout
4 xmlns:android= "Http://schemas.android.com/apk/res/android"
5 android:orientation= "Horizontal"
6 android:layout_width= "Fill_parent"
7 android:layout_height= "Fill_parent"
8 android:padding= "10DP" >
9
<imageview android:id= "@+id/imgicon"
One android:layout_width= "Wrap_content"
android:layout_height= "Fill_parent"
Android:gravity= "Center_vertical"
Android:layout_alignparenttop= "true"
Android:layout_alignparentbottom= "true"
android:layout_marginright= "15DP"
android:layout_margintop= "5DP"
android:layout_marginbottom= "5DP"/>
19
<textview android:id= "@+id/txttitle"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
Android:gravity= "Center_vertical"
Android:layout_alignparenttop= "true"
Android:layout_alignparentbottom= "true"
Num android:textstyle= "Bold"
Android:textsize= "22DP"
Android:textcolor= "#000000"
android:layout_margintop= "5DP"
android:layout_marginbottom= "5DP"/>
31
</LinearLayout>

In this article, I downloaded some icons in PNG format X 32 pixels. If you want, you can also use your own icon. Get your icons ready and put them in the drawable-mdpi file directory of your project. Next, create a new Java class in the project named Weather.java, which will be used for creating a custom Arrayadapter to bind the object to the ListView. Here's the code for the Weather.java file, which has two simple properties icon and title, and a normal constructor to initialize the property.

II. Development of Project procedures

To make it easier for everyone to understand, I drew the process structure:

Figure 3. Important Object Relational Structure

1 Weather.java Files:
2 public class Weather {
3 public int icon;
4 public String title;
5 public Weather () {
6 super ();
7}
8
9 Public Weather (int icon, String title) {
Super ();
One this.icon = icon;
This.title = title;
13}
14}

Note that the above Listview_item_row.xml file has two view, corresponding to the two properties of the weather class. The property values of the weather class are displayed in these two view. To connect the two view, you need to create a custom arrayadapter that inherits the Android Arrayadapter class and rewrites the GetView method. Add a new Java class to your project, named Weatheradapter, with the specific implementation code as follows:


1 Weatheradapter.java Files:
2 public class Weatheradapter extends arrayadapter<weather>{
3
4 context;
5 int Layoutresourceid;
6 Weather data[] = null;
7
8 Public Weatheradapter (context context, int Layoutresourceid, weather[] data) {
9 Super (context, layoutresourceid, data);
Ten This.layoutresourceid = Layoutresourceid;
One this.context = context;
This.data = data;
13}
14
@Override
Public View GetView (int position, View Convertview, ViewGroup parent) {
View row = Convertview;
Weatherholder holder = null;
19
if (row = null)
21 {
Layoutinflater Inflater = ((activity) context). Getlayoutinflater ();
row = Inflater.inflate (Layoutresourceid, parent, false);
24
Holder = new Weatherholder ();
Holder.imgicon = (ImageView) Row.findviewbyid (R.id.imgicon);
Holder.txttitle = (TextView) Row.findviewbyid (r.id.txttitle);
28
Row.settag (holder);
30}
Or else
32 {
Holder = (weatherholder) row.gettag ();
34}
35
Weather Weather = data[position];
Panax Notoginseng Holder.txtTitle.setText (weather.title);
Holder.imgIcon.setImageResource (Weather.icon);
39
return row;
41}
42
The Static class Weatherholder
44 {
ImageView Imgicon;
TextView Txttitle;
47}
48}

In the above code, the first thing that is more important is that the constructor of the class has three parameters, and the first parameter is the context object (we can pass the reference to the activity object that currently uses the Weatheradapter Class). The second parameter is the ID of the resource (which is the ID of the layout file that we want to use to render each ListView item), and in this article I will pass the listview_item_ I created Mainactivity.this The ID of the row.xml layout file; The third parameter is an array of weather objects that provide a data source for the adapter adapter to display the data.

Arrayadapter's GetView method has been rewritten. This method will be ListView each item item to create view views, and their properties are set by us. The GetView method also uses a temporary holder class (inner class declared within the Weatheradapter Class) that will be used to cache ImageView and TextView so that they can be reused for each row in the ListView, This will also give us a huge performance boost, and we don't have to find the two controls for each ListView item because we are constantly accessing the properties of the two identical views (ImageView and TextView). The code above also uses the Android built-in layoutinflator to parse XML layout files (for dynamically loading XML layout files so that they can find the content).

The last bit of code is the mainactivity we use. Inside, we use all of the objects declared above. The following is the code for the Mainactivity.java file:

Mainactivity.java file:
2 public class Mainactivity extends activity {
3
4 private ListView ListView1;
5
6 @Override
7 public void OnCreate (Bundle savedinstancestate) {
8 Super.oncreate (savedinstancestate);
9 Setcontentview (R.layout.main);
10
One Weather weather_data[] = new weather[]
12 {
New Weather (R.drawable.weather_cloudy, "cloudy"),
New Weather (r.drawable.weather_showers, "showers"),
New Weather (R.drawable.weather_snow, "Snow"),
New Weather (R.drawable.weather_storm, "Storm"),
New Weather (R.drawable.weather_sunny, "Sunny")
18};
19
Weatheradapter adapter = new Weatheradapter (This,
R.layout.listview_item_row, Weather_data);
22
23
ListView1 = (ListView) Findviewbyid (R.ID.LISTVIEW1);
25
View Header = (view) getlayoutinflater (). Inflate (R.layout.listview_header_row, NULL);
Listview1.addheaderview (header);
28
Listview1.setadapter (adapter);
30}

There are several areas in the Mainactivity.java file that need to be explained so that you can better understand them. First, we create an array of weather objects, and the icon and title are passed as arguments to its constructor; next, the Weatheradapter object is created, listview_item_ The ID of the Row.xml file and an array of weather objects are passed to its constructor. Again, we use the Android Layoutinflator to parse the listview_item_row.xml layout file. Sets the header information for the ListView through the ListView Addheaderview method. Finally, we pass the custom adapter to the ListView Setadapter method. We can build and run the project by now. If all is true, you will see the following.

Figure 2. Run effect

It's a sin not to write anything recently. There are some improper translation in the inevitable, we learn from each other. Respect the original, respect the knowledge, believe the power of sharing!

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.