使用ArrayAdapter
ArrayAdapter是将一个String类型的数组作为ListView控件的Item。
使用方法:
首先先在布局文件中声明ListView控件
<ListView
android:id="@+id/lv_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
></ListView>
然后创建一个android的xml,该文件中的内容只能有 xml的声明 和一个TextView控件。
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:textColor="#000000"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</TextView>
在代码Activity类中获取ListView的控件,并创建ArrayAdapter适配器。
String[] arr = {"一条短信.","二条短信,","三条短信..","四条短信."}; //元数据
ListView lv = this.findViewById(R.id.lv_list); //获取ListView控件。
//创建ArrayAdapter适配器
ArrayAdapter<String> arrAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.activity_item,arr);
//为ListView设置适配器。
lv.setAdapter(arrAdapter);
添加ListView条目的点击事件
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),arr[position],Toast.LENGTH_SHORT).show();
}
});