Example to explain the basic use and optimization of ListView in Android app development _android

Source: Internet
Author: User
Tags static class

First, use the ListView component directly to create
1. Create listview directly in XML enclose an array resource with the entries attribute
Where the divider property is to set the split line to use color and drawable resource segmentation

 <listview
    android:id= "@+id/listview1"
    android:layout_width= "match_parent"
    android:layout_height = "Wrap_content" 
    android:divider= "#33000000"
    android:dividerheight= "0.2DP"
    android: Footerdividersenabled= "true"
    android:headerdividersenabled= "true"
    android:entries= "@arrary/ctype" >
  </ListView>

Define an array resource file under values Arrays.xml

<resources>
<item > Scene mode 1</item>
<item > Scene pattern 2</item> 
<item > Scenario Mode 3</item>
</resources>

2. Create Arrayadapter Specify the list items to display
associating adapters in the Oncreat method

Simple_list_item_1: List items are normal text

Simple_list_item_2: Plain text font slightly larger for list items
simple_list_item_checked: The list item is one of the selected
Simple_list_item_multiple_choice: List item with check box
Simple_list_item_single_choice: List items with radio buttons

ListView = (ListView) Findviewbyid (R.id.listview1);
 arrayadapter<charsequence> adapter = Arrayadapter.createfromresource (This,r.array.ctype, Android. r.layout.simple_list_item_checked);
    Listview.setadapter (adapter);

Second, let the activity inherit listactivity realization

public class Activitymain extends Listactivity {
  @Override
  protected void onCreate (Bundle savedinstancestate) {

    super.oncreate (savedinstancestate);
    String[] CType ={"1", "2", "3"}; 
    arrayadapter<string> adapter = new Arrayadapter<string> (this,android. R.layout.simple_list_item_1,ctype);
    Setlistadapter (adapter);

  }

  @Override
  protected void Onlistitemclick (ListView l, View v, int position, long id) {

    super.onlistitemclick (l, V , position, id);
  }




Iii. use of Simpleadapter and baseaapter (emphasis)
the use of Simpleadapter

Adding ListView components to Main.xml
Write a layout file for layout list item content Items.xml
Create a simple adapter to associate with the ListView

 <?xml version= "1.0" encoding= "Utf-8"?> <linearlayout "xmlns:android=" Schemas.android.com/apk/res/android "android:orientation=" horizontal "android:layout_width=" Match_parent "Android : layout_height= "Match_parent" > <imageview android:id= "@+id/image" android:paddingright= "10px" Android:paddin gtop= "20px" android:paddingbottom= "20px" android:adjustviewbounds= "true" android:maxwidth= "72px" android:maxheight = "72px" android:layout_height= "wrap_content" android:layout_width= "wrap_content"/> <textview T_width= "Wrap_content" android:layout_height= "wrap_content" android:padding= "10px" android:layout_gravity= "center "Android:id=" @+id/title "/> </LinearLayout> 
public class Mainactivity extends activity {@Override public void onCreate (Bundle savedinstancestate) {Super.on
    Create (savedinstancestate);
    Setcontentview (R.layout.main); ListView ListView = (ListView) Findviewbyid (R.ID.LISTVIEW1); Get list view int[] imageID = new int[] {r.drawable.img01, r.drawable.img02, r.drawable.img03, R.drawable.img04, R.DRAWABLE.IMG05, r.drawable.img06, r.drawable.img07, r.drawable.img08}; Defines and initializes an array of saved picture IDs string[] title = new string[] {"Privacy settings", "Security", "System Settings", "Internet access", "My Documents", "GPS navigation", "My Music", "E-mai L "}; Defines and initializes an array of saved list item literals list<map<string, object>> ListItems = new arraylist<map<string, object>> () ; Create a list collection//In the For loop, place the picture ID and list item text in the MAP and add it to the list collection for (int i = 0; i < imageid.length i++) {map<s Tring, object> map = new hashmap<string, object> ();
      Instantiate the Map object Map.put ("image", imageid[i]);
      Map.put ("title", Title[i]); Listitems.add (map); //Add a Map object to the list collection} Simpleadapter adapter = new Simpleadapter (this, ListItems, R.layout.items, new string[ ] {"title", "Image"}, new int[] {r.id.title, r.id.image}); Create Simpleadapter Listview.setadapter (adapter);

 Associating adapters with ListView}}

III, Baseadapter usage, and ListView optimizations
using the same method as the main baseadapter is more flexible and more powerful, you can add other controls to it.

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "> <imageview android:id="
    @+id/imageview1 "android:layout_width=" 50dip "android:layout_height=" 50dip "android:layout_marginleft=" 5dip " android:layout_margintop= "5dip" android:layout_marginbottom= "5dip" android:src= "@android:d Rawable/ic_lock_po Wer_off "/> <textview android:id= @+id/textview1" android:layout_width= "Wrap_content" Android:layout_ height= "Wrap_content" android:layout_above= "@+id/textview2" android:layout_torightof= "@+id/imageView1" Android : text= "name" android:textcolor= "#000000" android:textsize= "20sp"/> <textview android:id= "@+id/textvi Ew2 "android:layout_width=" wrap_content "android:layout_height=" wrap_content "android:layout_alignbottom=" @+id /imageview1 "Android:layout_torightof= "@+id/imageview1" android:text= "number" android:textcolor= "#000000" android:textsize= "20sp"/>

 </RelativeLayout>
public class Mainactivity extends activity {private ListView LV;
  Private list<myinfo> infos;

  Private Random Random;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
    LV = (ListView) Findviewbyid (R.ID.LISTVIEW1);
Infos = new arraylist<myinfo> ();
      Add name and number to the list collection with a For loop for (int i = 0; i < i++) {MyInfo userInfo = new MyInfo ();
      Userinfo.setname ("name" +i);
      Userinfo.setnumber ("number" +i);
      Infos.add (UserInfo);  
    System.out.println (Userinfo.tostring ());
  } lv.setadapter (New Myadapter ()); Private class Myadapter extends baseadapter{@Override public int GetCount () {return infos.size (); Back to ListView length} @Override public View getview (int position, View Convertview, ViewGroup parent) {MyInfo
      UserInfo = Infos.get (position);
      View view;
     Viewholder Holder; Reduce the number of times a View object is created in memory if (Convertview!= null && convertview instanceof relativelayout) {view = Conve rtview;//reuse the View object that has been reclaimed holder = (Viewholder) view.gettag ();//get their reference} else {view = View.inflate (g
        Etapplicationcontext (), r.layout.item_layout, NULL);//Convert layout file to view object holder = new Viewholder ();
        Save the ID to the holder object/Note is under view Findviewbyid HOLDER.IV = (imageview) View.findviewbyid (R.ID.IMAGEVIEW1);
        HOLDER.TV1 = (TextView) View.findviewbyid (R.ID.TEXTVIEW1);
        HOLDER.TV2 = (TextView) View.findviewbyid (R.ID.TEXTVIEW2);
      View.settag (Holder)///objects found their references when they were created in Holder} holder.tv1.setText (Infos.get (position). GetName ());
      Holder.tv2.setText (Infos.get (position). GetNumber ());
    return view;
    @Override public Object getitem (int position) {return null;
    @Override public long getitemid (int position) {return 0;    
}
  /* * View object's container record the memory address of the View object is equivalent to a Notepad/static class viewholder{TextView TV1;
    TextView TV2;
  ImageView IV; 
  } public class MyInfo {private String name; Private string number;//can also add bitmap @Override public string toString () {return "MyInfo [name=" + name + ", Numbe
  R= "+ number +"] ";
  Public String GetName () {return name;
  public void SetName (String name) {this.name = name;
  Public String GetNumber () {return number;
  public void Setnumber (String number) {this.number = number;

 }


}

Note: (Many people do not notice that the following statement is Findviewbyid under view, less view will result in null pointer exception)

HOLDER.IV = (ImageView) View.findviewbyid (R.ID.IMAGEVIEW1);

The principle of optimization is the dynamic cyclic reuse of ListView objects that have been recycled (after recycling for convertview), maintaining a dynamic balance of the number of ListView entries in an interface. (Specific content Reference code comments can)

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.