ActivityListView.java
package?com.example.arrayadpterdemo;
import?java.util.ArrayList;
import?java.util.HashMap;
import?java.util.List;
import?java.util.Map;
import?android.os.Bundle;
import?android.widget.ListView;
import?android.widget.SimpleAdapter;
import?android.app.Activity;
public?class?MainActivity?extends?Activity?{
ListView?listView;
List<Map<String,?Object>>?data;
@Override
protected?void?onCreate(Bundle?savedInstanceState)?{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
listView?=?(ListView)?findViewById(R.id.listView);
/*
?*?
?*?//新建一個適配器,并添加數據源?String[]?data?=
?*?{"Items1","Items2","Items3","Items4"};?ArrayAdapter<String>
?*?arr_Adpter?=?new?ArrayAdapter<String>(this,
?*?android.R.layout.simple_expandable_list_item_1,?data);?//視圖加載適配器
?*?listView.setAdapter(arr_Adpter);
?*/
//新建適配器+加載數據源
List<Map<String,?Object>>?data?=?new?ArrayList<Map<String,?Object>>();
SimpleAdapter?sp_Adapter?=?new?SimpleAdapter(this,?getData(),
R.layout.alayout,?new?String[]?{?"pic",?"word"?},
new?int[]?{?R.id.pic,?R.id.word?});
//視圖加載適配器
listView.setAdapter(sp_Adapter);
}
//獲取數據源
private?List<Map<String,?Object>>?getData()?{
for?(int?i?=?0;?i?<?10;?i++)?{
Map<String,?Object>?map?=?new?HashMap<String,?Object>();
map.put("pic",?R.drawable.ic_launcher);
map.put("word",?"123");
data.add(map);
}
return?data;
}
}
alaout.xml
<?xml?version="1.0"?encoding="utf-8"?>
<LinearLayout?xmlns:android="http://schemas.android.com/apk/res/android"
????android:layout_width="match_parent"
????android:layout_height="match_parent"
????android:orientation="horizontal"?>
????<ImageView
????????android:id="@+id/pic"
????????android:layout_marginLeft="20dp"
????????android:layout_width="wrap_content"
????????android:layout_height="wrap_content"
????????android:src="@drawable/ic_launcher"?/>
????<TextView
????????android:gravity="center_horizontal"
????????android:layout_marginTop="10dp"
????????android:id="@+id/word"
????????android:layout_width="fill_parent"
????????android:layout_height="30dp"
????????android:text="Android?Robot"
????????android:textSize="20sp"?
????????/>
</LinearLayout>
activity_listview
<?xml?version="1.0"?encoding="utf-8"?>
<LinearLayout?xmlns:android="http://schemas.android.com/apk/res/android"
????android:layout_width="match_parent"
????android:layout_height="match_parent"
????android:orientation="vertical"?>
????<ListView
????????android:id="@+id/listView"
????????android:layout_width="match_parent"
????????android:layout_height="wrap_content"?>
????</ListView>
</LinearLayout>

2016-09-27
data是成員變量,你在oncreate()方法里面又重新寫了個data,相當于一個局部變量,在獲取數據源的方法中添加數據到data(全局變量的data),但是你全局的data并沒有初始化,而且數據距適配器中的data并沒有數據。建議你將oncreate()方法中List<Map<String,?Object>>?data?=?new?ArrayList<Map<String,?Object>>();改為data?=?new?ArrayList<Map<String,?Object>>();
2016-09-25
你getdata()方法是模擬假數據的 ?后面一個換成map.put("word"+i);
2016-09-25
你定義在onCreate外的data并沒有new,而onCreate里創建的這個data根本沒使用。
求采納!
2016-09-22
那異常貼出來啊