The most common and hardest widget
• First,creat in layout layer
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
○ match_parent denote fill all the space in the layout
○ wrap_content denote the smallest area which can contain the content
• The data can not deliver to ListView directly, we need adapter, the best adapter is ArrayAdapter.
○ It use genericity(泛型) to assign(指定) the data which need to be delivered,then we deliver the data in the constructor(构造函数)
○ In the case, the data we used are all strings, so we set the genericity as String
○ Then, we should deliver current context(当前上下文), the id in subitem layout(子项布局的ID), the data need to be adapted(要适配的数据)
§ Tips: we use the android.R.layout.simple_list_item_1 as subitem layout ID, it's a bulit-in layout file in Android, there is only one TextView which can simplily show a piece of character
• CASE:
//------以下为一个最简单的(使用字符串数组)的ListView------
private String[] data = {
"Apple","Banana","Orange","Watermelon","Pear","Grape","Pineapple","Strawberry","Cherry","Mango",
"Apple","Banana","Orange","Watermelon","Pear","Grape","Pineapple","Strawberry","Cherry","Mango"
};
@Override
protectedvoidonCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<String>adapter=newArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, data);
ListView listView = (ListView)findViewById(R.id.list_view);
listView.setAdapter(adapter);
}
}