Android Introduction (v) ui-units and dimensions, ListView

Source: Internet
Author: User
Tags pear

Original link: http://www.orlion.ga/453/

I. Units and dimensions

There are altogether the following units in the layout file: px,pt,dp,sp

PX: is the smallest element unit in pixels that is visible in the screen.

PT: Is a pound, 1 lbs equals 1/72 inches, the general PT will be used as the unit of the font.

The same PX number of controls at different resolutions on the phone screen effect is different, PT and PX is the same situation

DP: is a density-independent pixel, also known as a dip, that is consistent in proportion to a screen of different densities compared to PX

SP: is a scalable pixel, using the same design concept as DP, solve the problem of text size adaptation

The density in Android is the number of pixels in the screen without inches, usually in dpi, such as a phone screen width is 2 inches long is 3 inches, if its resolution is 320*480 pixels, then the phone's screen is 160dpi, if the resolution is 640* 960, then the density of this screen is 320dpi.

According to Android rules, on the 160dpi screen 1DP equals 1px, and on the 320dpi screen 1DP equals 2px.

Second, the ListView

1. Simple usage of the ListView

Start by creating a new Listviewtest project and have ADT automatically help us create a good activity. And then Modify

The code in Activity_main.xml is as follows:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_parent" android:layout_height= "Match_parent" > <listview android:id= "@+id/list_view" android:layout_width= " Match_parent "android:layout_height=" match_parent "> </ListView></LinearLayout>

Next, modify the code in Mainactivity as follows:

public class mainactivity extends activity {    private  string[] data = {  "Apple",  "Banana",  "Orange",  "Watermelon",          "Pear",  "Grape",  "Pineapple",  "Strawberry",  "Cherry",   "Mango"  };     @Override     protected void  OnCreate (bundle savedinstancestate)  {        super.oncreate ( Savedinstancestate);         setcontentview (R.layout.activity_main);         ArrayAdapter<String> adapter = new  Arrayadapter<string> (             Mainactivity.this, android. R.layout.simple_list_item_1, data);         listview listview  =  (ListView)  findviewbyid (R.id.list_view);         Listview.setadapter (adapter);     }}

Now that the ListView is used to show a lot of data, we should provide the data first. This data can be downloaded from the Web or read from the database, and should be determined by the specific application scenario. Here we simply use a data array to test, which contains a lot of fruit names.

However, the data in the array cannot be passed directly to the ListView, and we need the adapter to do it. There are many implementations of adapters available in Android, which I think is best used for arrayadapter. It can specify the data type to be adapted by generics, and then pass the data to be adapted in the constructor. Arrayadapter has multiple overloads of constructors, you should choose the most appropriate one based on the actual situation. This is because the data we provide is a string, so the generic type of Arrayadapter is specified as String, and then in the constructor of Arrayadapter, the current context, the ID of the ListView child layout, and the data to be adapted are sequentially passed in. Note that we are using Android. R.layout.simple_list_item_1 as the ID of the ListView child layout, this is an Android built-in layout file with only one TextView that can be used to simply display a piece of text. This allows the adapter object to be built. Finally, you need to call the ListView Setadapter () method to pass the built-in adapter object so that the correlation between the ListView and the data is complete. Now run the program,

2. Add a picture to the ListView

A ListView that can only display a piece of text is just too dull, and we can now customize the ListView interface to allow it to display richer content. First of all, we need to prepare a set of pictures, corresponding to each of the fruits provided above, we will let these fruit names next to a pattern. Next, define an entity class as the adapter type for the ListView adaptor. To create a new class Fruit, the code looks like this:

public class Fruit {private String name;    private int imageId;        Public Fruit (String name, int imageId) {this.name = name;    This.imageid = imageId;    } public String GetName () {return name;    } public int Getimageid () {return imageId; }}

There are only two fields in the fruit class, name indicates the name of the fruit, and imageID represents the resource ID of the fruit corresponding to the picture. Then you need to specify a custom layout for the child of the ListView, create a new fruit_item.xml in the layout directory, and the code looks like this:

<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"      Android:layout_width= "Match_parent"     android:layout_height= "Match_parent"  >     <imageview        android:id= "@+id/fruit_ Image "        android:layout_width=" Wrap_content "         android:layout_height= "Wrap_content"  />    < Textview        android:id= "@+id/fruit_name"          android:layout_width= "Wrap_content"          android:layout_height= "Wrap_content"         android:layout_gravity= " Center "        android:layout_marginleft=" 10dip " /></ Linearlayout>

In this layout, we define a ImageView for displaying fruit, and a textview for displaying the name of the fruit.

Next, you need to create a custom adapter that inherits from Arrayadapter and designates the generic as the fruit class. To create a new class Fruitadapter, the code looks like this:

public class fruitadapter extends arrayadapter<fruit> {     Private int resourceid;    public fruitadapter (Context context,  int textviewresourceid,        list<fruit> objects)  {        super (context, textviewresourceid, objects);         resourceId = textViewResourceId;     }     @Override     public view getview (int  Position, view convertview, viewgroup parent)  {         fruit fruit = getitem (position); //  Gets the Fruit instance of the current item          view view = layoutinflater.from (GetContext ()). Inflate (resourceId,  NULL); &NBSP;&NBSP;&NBSP;&Nbsp;    imageview fruitimage =  (ImageView)  view.findviewbyid ( R.id.fruit_image);        textview fruitname =  ( TextView)  view.findviewbyid (r.id.fruit_name);         Fruitimage.setimageresource (Fruit.getimageid ());         Fruitname.settext (Fruit.getname ());        return view;     }}

The

    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 child is scrolled into the screen. In the GetView method, we first get the fruit instance of the current item through the GetItem () method, then use Layoutinflater to load our incoming layout for this subkey, and then call the view's Findviewbyid () method to obtain the ImageView and TextView instances, and call their Setimageresource () and SetText () methods respectively to set the displayed picture and text, and finally return the layout so that our custom adapter is complete. The following changes the code in Mainactivity as follows:

Public class mainactivity extends activity {    private list <Fruit> fruitList = new ArrayList<Fruit> ();     @Override     protected void oncreate (bundle savedinstancestate)  {         super.oncreate (savedinstancestate);         setcontentview (R.layout.activity_main);         initfruits ( ); //  Initialize fruit data         FruitAdapter adapter =  New fruitadapter (Mainactivity.this,        r.layout.fruit_item,  fruitlist);        listview listview =  (ListView)  findviewbyid (R.id.list_view);         listview.setadapter (Adapter );    }    private void initfruits ()  {         fruit apple = new fruit ("Apple",  r.drawable.apple_pic);         fruitlist.add (apple);        fruit  Banana = new fruit ("banana",  r.drawable.banana_pic);         fruitlist.add (banana);         fruit orange =  new fruit ("Orange",  r.drawable.orange_pic);         Fruitlist.add (orange);         fruit watermelon = new  fruit ("Watermelon",  r.drawable.watermelon_pic);         Fruitlist.add (watermelon);         fruit pear = new  fruit ("Pear",  r.drawaBle.pear_pic);         fruitlist.add (pear);         fruit grape = new fruit ("Grape",  r.drawable.grape_pic);         fruitlist.add (grape);         fruit pineapple = new fruit ("Pineapple",  r.drawable.pineapple_pic);         fruitlist.add (Pineapple);         Fruit strawberry = new fruit ("Strawberry",  r.drawable.strawberry_pic);         fruitlist.add (Strawberry);         Fruit cherry = new fruit ("Cherry",  r.drawable.cherry_pic);         fruitlist.add (cherry);         fruit mango  = new fruiT ("Mango",  r.drawable.mango_pic);         fruitlist.add (Mango);     }}

As you can see, a initfruits () method is added here to initialize all the fruit data. In the constructor of the fruit class, the name of the fruit and the corresponding image ID are passed in, and the created object is added to the fruit list. We then created the Fruitadapter object in the OnCreate () method and passed the Fruitadapter as an adapter to the ListView. This completes the task of customizing the ListView interface. Re-run the program now

,

3, improve the operation efficiency of the ListView

The ListView control is very difficult to use, because it has a lot of detail to optimize, and the operational efficiency is very important. Our ListView is currently running at a low efficiency because the layout is reloaded once each time in the Fruitadapter GetView () method, which becomes a bottleneck for performance when the ListView is scrolling fast. Carefully observed, the GetView () method also has a Convertview parameter, which is used to load the previously loaded

The layout is cached so that it can be reused later. Modify the code in the Fruitadapter as follows:

public class fruitadapter extends arrayadapter<fruit> {     ......     @Override     public view getview (int position,  view convertview, viewgroup parent)  {         fruit fruit = getitem (position);         view  view;        if  (convertview == null)  {             view = layoutinflater.from ( GetContext ()). Inflate (Resourceid, null);        } else  {            view = convertview;         }        ImageView  fruitimage =  (ImageView) &Nbsp;view.findviewbyid (r.id.fruit_image);        textview  fruitname =  (TextView)  view.findviewbyid (r.id.fruit_name);         fruitimage.setimageresource (Fruit.getimageid ());         Fruitname.settext (Fruit.getname ());        return view;     }}

As you can see, we now judge in the GetView () method that if Convertview is empty, the layout is loaded using Layoutinflater, and if not empty, the Convertview is reused directly. This greatly improves the efficiency of the ListView, and can also show better performance in fast scrolling.

However, currently our code can continue to optimize, although it is no longer repeated to load the layout, but each time in the GetView () method will call the view's Findviewbyid () method to get the instance of the control. We can use a viewholder to optimize this part of the performance and modify the code in the Fruitadapter as follows:

public class fruitadapter extends arrayadapter<fruit> {     ......     @Override     public view getview (int position,  view convertview, viewgroup parent)  {         fruit fruit = getitem (position);         view  view;        ViewHolder viewHolder;         if  (convertview == null)  {             view = layoutinflater.from (GetContext ()). Inflate (ResourceId,  null);             viewholder = new  viewholder ();             viewholder.fruitimage =  (ImageView)   View.findviewbyid (R.id.fruit_image);             viewholder.fruitname =  (TextView)  view.findviewbyid (r.id.fruit_name);             view.settag (viewholder); //  store ViewHolder in view         } else {             view = convertView;             viewHolder =  (Viewholder)  view.gettag (); //  regain Viewholder         }         ViewHolder.fruitImage.setImageResource (Fruit.getimageid ());         ViewHolder.fruitName.setText (Fruit.getname ());         return view ;     }    class viewholder {        imageview fruitimage;         textview fruitname;    }}

We have added an internal class Viewholder to cache instances of the control. When Convertview is empty, create a Viewholder object and store the instance of the control in Viewholder, then call the view's Settag () method, storing the Viewholder object in the view. When Convertview is not empty, call the view's Gettag () method to remove the Viewholder. So that the instances of all the controls are in Viewholder, it is not necessary to get the control instance through the Findviewbyid () method every time. With this two-step optimization, our ListView is already running at a very good rate.

4. ListView Click event

The ListView's scrolling only satisfies our visual effect, but if the child in the ListView cannot be clicked, the control has no practical purpose. So in this section we'll learn how the ListView can respond to a user's click events. Modify the code in the mainactivity as follows:

Public class mainactivity extends activity {    private list <Fruit> fruitList = new ArrayList<Fruit> ();     @Override     protected void oncreate (bundle savedinstancestate)  {         super.oncreate (savedinstancestate);         setcontentview (R.layout.activity_main);         initfruits ( );         fruitadapter adapter = new fruitadapter ( Mainactivity.this,        r.layout.fruit_item, fruitlist);         ListView listView =  (ListView)  findviewbyid ( R.id.list_view);         listview.setadapter (adapter);       &nbSp; listview.setonitemclicklistener (New onitemclicklistener ()  {              @Override              public void onitemclick (Adapterview<?> parent, view view,                 int  Position, long id)  {                 fruit fruit = fruitlist.get (position);                 toast.maketext (MainActivity.this,  Fruit.getname (),                 toast.length_short). Show ();             }        &nbSP;}); &NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;&NBSP;&NBSP, ...}

As you can see, we used the Setonitemclicklistener () method to register a listener for the ListView, and when the user clicked on any one of the children in the ListView, The Onitemclick () method would be called back, in which case the The position parameter determines which subkey the user clicked on, then gets the corresponding fruit and displays the name of the fruit by toast. Run the program again and click on the watermelon

Android Introduction (v) ui-units and dimensions, ListView

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.