如何使用ListView来显示数据?
1.让MainActivity继承ListActivity类
2.在main_layout中定义一个Listview控件,并设置id为android:list(因为之后使用到的SimpleAdapter默认关联的id为list)
3.定义一个布局文件,用来规定ListView中的数据显示格式
4.添加数据
5.设置Adapter
MainActivity.java:
package com.mycompany.listview;
import android.app.ListActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SimpleAdapter adapter = new SimpleAdapter(this, getData(), R.layout.item,new String[]{"name", "number"}, new int[]{R.id.name, R.id.number});
setListAdapter(adapter);
}
private List<HashMap<String, String>> getData(){
// 生成List对象
List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
// 生成HashMap对象,用来存放一行数据
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", "police");
map.put("number", "110");
list.add(map); // 注意,此时add进去的只是map的引用
HashMap<String, String> map2 = new HashMap<String, String>();
map2.put("name", "doctor");
map2.put("number", "120");
list.add(map2);
HashMap<String, String> map3 = new HashMap<String, String>();
map3.put("name", "fireman");
map3.put("number", "119");
list.add(map3);
return list;
}
}
注意:
SimpleAdapter的构造函数的第一个参数为当前Activity;
第二个参数为List对象,我用getData()代替,getData()的作用就是为List对象添加数据,最后返回该List对象;
第三个参数为自定义的数据显示格式布局文件;
第四个参数为String数组,元素为所有要显示的键值对中的键;
第五个参数为Int数组,元素为自定义布局文件中用来显示数据的控件id。
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.mycompany.listview.MainActivity">
<ListView
android:id="@+id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
</RelativeLayout>
item.xml:(自定义的布局文件)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/name"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/number"
android:gravity="right"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</LinearLayout>