The ListView in Android is an important piece of content mastering the basic usage of the ListView plays an important role in learning Android
Let's introduce today three ways to populate the ListView with simple text to populate the usage of other data types.
First: Add data directly to the adapter
public class Mainactivity extends Activity {
PrivateListView lv1;PrivateArrayadapter<string>adapter;protected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Lv1=(ListView) Findviewbyid (R.ID.LV1); Adapter=NewArrayadapter<string> ( This, Android. R.layout.simple_list_item_1); Adapter.add ("Hello");//the third is to add data directly with adapter note to define adapter and add data to adapterAdapter.add ("Hello"); Adapter.add (Hello); Adapter.add (Hello); Adapter.add (Hello); Lv1.setadapter (adapter);
}
}
The second type: adding data through an array here is an example of string data
Public class Mainactivity extends Activity {
PrivateListView Lv1; PrivateArrayadapter<string>adapter; protected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Lv1=(ListView) Findviewbyid (R.ID.LV1); /*** Three ways to add data*/String data[]={"Hello", "Hello", "Hello"};//adding data through an arrayAdapter=NewArrayadapter<string> ( This, Android. R.layout.simple_list_item_1,data); Lv1.setadapter (adapter);}
}
The third type: Add data by collection The following is an example of string data
public class Mainactivity extends Activity {
PrivateListView Lv1; PrivateArrayadapter<string>Adapter @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Lv1=(ListView) Findviewbyid (R.ID.LV1); List<String> data1=NewArraylist<string> ();//adding data from a collectionData1.add ("Southwest University of Science and Technology"); Data1.add ("Southwest University of Science and Technology"); Data1.add ("Southwest University of Science and Technology"); Data1.add ("Southwest University of Science and Technology"); Adapter=NewArrayadapter<string> ( ThisAndroid. R.LAYOUT.SIMPLE_LIST_ITEM_1,DATA1); Lv1.setadapter (adapter);
}
}
2016.03.03 Learning notes three ways to populate a ListView with simple text