Android Learning notes (10)

Source: Internet
Author: User

Android Control--listview

The ListView allows the user to scroll off-screen data to the screen by swiping up and down the finger, while

The existing data on the screen will scroll out of the screen.

Simple usage of 1.ListView

Create a new Listviewtest project and modify the code in the Activity_main.xml as follows:

<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent" >    <ListViewAndroid:id= "@+id/list_view"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent">            </ListView></LinearLayout>

To add a ListView control to the layout, first specify an ID for the ListView, and then set the width and height to match_parent,

This allows the ListView to occupy the entire layout space.

Modify the code in the mainactivtity as follows:

//define an array    Privatestring[] data = {"Apple", "Banana", "Orange", "Watermelon", "Pear", "Grape",            "Pineapple", "Strawberry", "Cherry", "Mango"}; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); /** The data in the array cannot be passed directly to the ListView and needs to be done with an adapter.         * Arrayadapter can specify the data type to be adapted by generics, and then the data to be adapted in the constructor is passed in. */Arrayadapter<String> adapter =NewArrayadapter<string> (mainactivity. This, Android.        R.layout.simple_list_item_1, data); ListView ListView=(ListView) Findviewbyid (R.id.list_view); //Call the Setadapter () method of the ListView to pass the built-in adapter object in. Listview.setadapter (adapter); }}

In the code above, the data for the array cannot be passed directly to the ListView, which needs to be done with an adapter.

Arrayadapter can specify the data type to be adapted by generics, and then pass in the constructor the data to be fitted.

In the preceding code, the generic type of Arrayadapter is specified as String, and then in the constructor of Arrayadapter, the current

The ID of the context, the ListView child layout, and the data to be adapted.

Finally, call the Setadapter () method of the ListView to pass the built-in adapter object in.

2. Customizing the ListView Interface

Define an entity class, as an adaptation type for the ListView adapter, to create a new class fruit with the following code:

 Packagecom.mfeng.listviewtest; Public classFruit {PrivateString name; Private intimageId; //Fruit Constructors for class     PublicFruit (String name,intimageId) {         This. Name =name;  This. ImageId =imageId; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetimageid () {returnimageId; }     Public voidSetimageid (intimageId) {         This. ImageId =imageId; }        }

There are two fields in the fruit class, name indicates the name of the fruit, and imageID indicates the resource ID of the fruit corresponding to the picture.

You then need to specify a custom layout for the child of the ListView, in the layout directory

Create a new Fruit_item.xml file with the code as follows:

<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent" >        <ImageViewAndroid:id= "@+id/fruit_image"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content" />        <TextViewAndroid:id= "@+id/fruit_name"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:gravity= "Center"Android:layout_marginleft= "10dip" /></LinearLayout>

In this layout, a imageview is defined to display a picture of the fruit, and a textview is used to display the name of the fruit.

Next you need to create a custom adapter that inherits from Arrayadapter and assigns the generic type

For the fruit class, create a new class Fruitadapter, as shown in the following code:

 Packagecom.mfeng.listviewtest;Importjava.util.List;ImportAndroid.content.Context;ImportAndroid.view.LayoutInflater;ImportAndroid.view.View;ImportAndroid.view.ViewGroup;ImportAndroid.widget.ArrayAdapter;ImportAndroid.widget.ImageView;ImportAndroid.widget.TextView; Public classFruitadapterextendsArrayadapter<fruit> {        Private intresourceId; //overriding a set of constructors for a parent class     PublicFruitadapter (Context context,intTextviewresourceid,list<fruit>objects) {        Super(Context, Textviewresourceid, objects); ResourceId=Textviewresourceid; }        //override the GetView () method, which is called when each subkey is scrolled into the screen     PublicView GetView (intPosition,view Convertview,viewgroup Parent) {        //Gets the fruit instance of the current itemFruit Fruit =GetItem (position); View View= Layoutinflater.from (GetContext ()). Inflate (ResourceId,NULL); ImageView Fruitimage=(ImageView) View.findviewbyid (r.id.fruit_image); TextView Fruitname=(TextView) View.findviewbyid (r.id.fruit_name); //call the Setimageresource and SetText () methods to set the displayed picture and textFruitimage.setimageresource (Fruit.getimageid ());                Fruitname.settext (Fruit.getname ()); //return to Layout        returnview; }}

Fruitadapter overrides a set of constructors for the parent class to pass in the ID and data of the context, ListView child layout.

It also overrides the GetView () method, which is called when each subkey is scrolled into the screen.

In the GetView () method, the fruit instance of the current item is first obtained through the GetItem () method, and then the layoutinflater is used to

This subkey loads our incoming layout, and then calls the view's Findviewbyid () method to get to the ImageView and

TextView instances, and call their Setimageresource () and SetText () methods to set the displayed picture and text, respectively,

Finally, the layout is returned so that the custom adapter is complete.

Modify the code in the mainactivity as follows:

 Public classMainactivityextendsActivity {PrivateList<fruit> fruitlist =NewArraylist<fruit>(); //Initializing fruit Datainitfruits (); Fruitadapter Adapter=NewFruitadapter (mainactivity. This, R.layout.fruit_item, fruitlist); ListView ListView=(ListView) Findviewbyid (R.id.list_view);            Listview.setadapter (adapter); }//Add a Initfruit () method to initialize all fruit data    Private voidinitfruits () {Fruit Apple=NewFruit ("Apple", R.drawable.apple_pic);        Fruitlist.add (Apple); Fruit Banana=NewFruit ("Banana", R.drawable.banana_pic);        Fruitlist.add (banana); Fruit Orange=NewFruit ("Orange", R.drawable.orange_pic);        Fruitlist.add (orange); Fruit Pineapple=NewFruit ("Pineapple", R.drawable.pineapple_pic);    Fruitlist.add (pineapple); }

In the above code, a Initfruits () method is added to initialize all fruit data. In the constructor of the fruit class

Pass in the name of the fruit and the corresponding picture ID, and then add the created object to the fruit list.

3. Improve the operation efficiency of the ListView

The GetView () method has a Convertview parameter, which is used to cache the previously loaded layout so that

can then be reused.

Modify the code in the Fruitadapter as follows:

 Packagecom.mfeng.listviewtest;Importjava.util.List;ImportAndroid.content.Context;ImportAndroid.view.LayoutInflater;ImportAndroid.view.View;ImportAndroid.view.ViewGroup;ImportAndroid.widget.ArrayAdapter;ImportAndroid.widget.ImageView;ImportAndroid.widget.TextView; Public classFruitadapterextendsArrayadapter<fruit> {        Private intresourceId; //overriding a set of constructors for a parent class     PublicFruitadapter (Context context,intTextviewresourceid,list<fruit>objects) {        Super(Context, Textviewresourceid, objects); ResourceId=Textviewresourceid; }        //override the GetView () method, which is called when each subkey is scrolled into the screen     PublicView GetView (intPosition,view Convertview,viewgroup Parent) {        //Gets the fruit instance of the current itemFruit Fruit =GetItem (position);                View view;                Viewholder Viewholder; //The GetView () method has a Convertview parameter, which is used to cache the previously loaded layout.         if(Convertview = =NULL) {View= Layoutinflater.from (GetContext ()). Inflate (ResourceId,NULL); //Create a Viewholder objectViewholder =NewViewholder (); //gets the ID of the FruitimageViewholder.fruitimage =(ImageView) View.findviewbyid (r.id.fruit_image); //gets the ID of the FruitnmaeViewholder.fruitname =(TextView) View.findviewbyid (r.id.fruit_name); //store Viewholder in viewView.settag (Viewholder); }Else{View=Convertview; Viewholder=(Viewholder) View.gettag (); }                //call the Setimageresource and SetText () methods to set the displayed picture and textViewHolder.fruitImage.setImageResource (Fruit.getimageid ());                ViewHolder.fruitName.setText (Fruit.getname ()); //return to Layout        returnview; }        //a new inner class Viewholder is added to cache instances of the control.     classViewholder {ImageView fruitimage;    TextView Fruitname; }}

In the above code, an internal class Viewholder is added to cache the instance of the control, and when Convertview is empty,

Create a Viewholder object and store the instance of the control in Viewholder, then call the view's Settag () method,

Stores the Viewholder object in the view.

When Convertview is not empty, call the view's Gettag () method to remove the Viewholder. This allows the control to be cached in the Viewholder

, it is not necessary to get an instance of the control through the Findviewbyid () method.

4.ListView of Click events. Modify the code in the mainactivity as follows:

// to set the listener        for a ListView Listview.setonitemclicklistener (new  Onitemclicklistener () {            @Override            public void Onitemclick (adapterview<?> Parent, view view,                    intlong  ID) {                = fruitlist.get (position);                Toast.maketext (mainactivity.  This , Fruit.getname (), Toast.length_short). Show ();                            }        );

In the code above, use the Setonitemclicklistener () method to register a listener for the ListView.

Android Learning Note (10)

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.