Android 0 Basics Section 40th: Customizing Arrayadapter

Source: Internet
Author: User

The ListView is still relatively simple and the most important component in Android apps, but other ListView can do as much as you want, and that's what we're going to learn next.

One, custom Arrayadapter

From the previous Period custom list item example knows that each list item's icon is the same, if needs each list item's icon according to the content dynamic representation, the Android system's Arrayadapter is powerless, can only use the custom Arrayadapter to implement.

This is done by creating a arrayadapter subclass, overriding its GetView () method, and then building a different list item. where the GetView () method returns a view, which is the row corresponding to the adapter data.

Before learning to customize Arrayadapter, come together to learn about the Layoutinflater class first. It is still very useful to layoutinflater this class in real-world development, which acts like Findviewbyid (). The difference is that Layoutinflater is used to find and instantiate an XML layout file under Res/layout/, while Findviewbyid () is looking for specific widget controls (such as button, TextView, and so on) under the XML layout file.

Layoutinflater is an abstract class that obtains layoutinflater instances in the following three ways.

// get through Activity layoutinflaterinflater=getlayoutinflater (); // Get by static method layoutinflaterinflater=layoutinflater.from (context); // get through system service layoutinflaterinflater= (layoutinflater) context.getsystemservice (Context.layout_inflater_service);

In fact, the final essence of these three methods is to call the Context.getsystemservice (), the use of the method will be in the subsequent content of learning.

Once you have the Layoutinflater instance, you can call the Inflater.inflater () method to find and instantiate the layout file, which is often used to get each item layout for the ListView.

Ii. examples

Next use an example to learn how to customize Arrayadapter, and you need to override the GetView () method to display different icons based on content in different pairs of rows. The icon to be displayed is based on the first letter of the string displayed, and if you start with the letter "a" or "a", an icon for the letter A is displayed.

Continue to use the Listviewsample module of the Widgetsample project to create a custom_arrayadapter_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">    <ListViewAndroid:id= "@+id/listview"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content" /></LinearLayout>

Then create a new custom_arrayadapter_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:orientation= "Horizontal"android:gravity= "Center_vertical">    <ImageViewAndroid:id= "@+id/letter_img"Android:layout_width= "50DP"Android:layout_height= "50DP"android:padding= "5DP"android:src= "@mipmap/ic_launcher"/>    <TextViewAndroid:id= "@+id/content_tv"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:textsize= "24SP"Android:textcolor= "#b6400e"/></LinearLayout>

Then create a Myarrayadapter class, inherit the Arrayadapter class, override the GetView () method, with the following code:

 PackageCom.jinyu.cqkxzsxy.android.listviewsample.adapter;Importandroid.app.Activity;ImportAndroid.support.annotation.NonNull;ImportAndroid.view.LayoutInflater;ImportAndroid.view.View;ImportAndroid.view.ViewGroup;ImportAndroid.widget.ArrayAdapter;ImportAndroid.widget.ImageView;ImportAndroid.widget.TextView;ImportCOM.JINYU.CQKXZSXY.ANDROID.LISTVIEWSAMPLE.R;/*** @ Creator Xin 鱻 * @ description Android 0 Basic primer to Master Series tutorials, welcome to the public number Shareexpert*/ Public classMyarrayadapterextendsArrayadapter {PrivateActivity Mcontext =NULL;//Contextual Environment    Private intMresourceid;//list item layout resource ID    PrivateString[] Mitems;//List Content Array     PublicMyarrayadapter (Activity context,intresId, string[] items) {        Super(context, resId, items); //Save ParametersMcontext =context; Mresourceid=resId; Mitems=items; } @NonNull @Override PublicView GetView (intposition, View Convertview, ViewGroup parent) {        //Get Layoutinflater ObjectLayoutinflater Inflater =Mcontext.getlayoutinflater (); //Load list Item ViewView Itemview = inflater.inflate (Mresourceid,NULL); //get the components of a list itemTextView Contenttv =(TextView) Itemview.findviewbyid (R.ID.CONTENT_TV); ImageView letterimg=(ImageView) Itemview.findviewbyid (r.id.letter_img); //remove the data to be displayedString content =Mitems[position].trim (); //setting display values for TextViewContenttv.settext (content); //determine the icon to display based on the first letter of the content        if(Content.startswith ("a") | | content.startswith ("a")) {letterimg.setimageresource (r.drawable.letter_a); } Else if(Content.startswith ("B") | | content.startswith ("b")) {letterimg.setimageresource (r.drawable.letter_b); } Else if(Content.startswith ("C") | | content.startswith ("C")) {letterimg.setimageresource (r.drawable.letter_c); } Else if(Content.startswith ("D") | | content.startswith ("D")) {letterimg.setimageresource (r.drawable.letter_d); } Else if(Content.startswith ("E") | | content.startswith ("e")) {letterimg.setimageresource (r.drawable.letter_e); }        //returns the list item view        returnItemview; }}

In the preceding code, the GetView () method is overridden to return a list item based on the object being displayed, where the object is represented by the position index in adapter.

The view object obtained through Layoutinflater is actually composed of a list item layout file that contains the linearlayout of ImageView and TextView. Then find the ImageView and TextView components, fill in the contents to TextView, and determine the letter icon ImageView to be displayed based on the first letter of the content.

Next, provide adapter for the ListView and use the custom Arrayadapter to determine which list items the ListView will display. Create a new Customarrayadapteractivity.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.widget.ListView;ImportCom.jinyu.cqkxzsxy.android.listviewsample.adapter.MyArrayAdapter; Public classCustomarrayadapteractivityextendsappcompatactivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (r.layout.custom_arrayadapter_layout); //Get interface ComponentsListView ListView =(ListView) Findviewbyid (R.id.listview); //define the array to displayString[] contents = {"Android", "Demo", "Edit", "APP", "Excel",                "DotA", "button", "Circle", "Excel", "Back"}; //wrapping an array as a custom MyarrayadapterMyarrayadapter adapter =NewMyarrayadapter ( This, R.layout.custom_arrayadapter_item, contents); //set adapter for the ListViewListview.setadapter (adapter); }}

You can see that the steps to use the custom Arrayadapter and the Android native Arrayadapter are the same.

Modify the activated activity, run the program, you can see the interface effect shown.

As can be seen, this is obviously more practical than the previous example interface, you can dynamically display the contents of the list items, you can design a very beautiful list page.

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

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.