/**
* 正确示范二(正确运用,Activity里面对象不用作Adapter原始对象,只做数据的备份。
* 这也是本人比较喜欢的写法,原因:很多时候我们会不经意间改变Activity里面的数据源后导致ListView的改变,
* 导致出错后排除错误难解<正确示范一,当然也有好处,比如:改变Activity数据后,不需要再做多余的Adapter数据的更改,方便>)
*
* @注意 这里只是数据添加方案本人赞成写法,具体完整结合adapter请移步个人推荐一或二<有错误示范,才能慢慢完善改变,错误何尝不是一种成长>
* @author johnny
*
*/
public
class
FourListViewActivity
extends
Activity {
private
ListView mContentLv;
private
OneAdapter adapter;
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
mContentLv = (ListView) findViewById(R.id.lv_content);
adapter=
new
OneAdapter(
this
);
mContentLv.setAdapter(adapter);
initData();
ToastUtils.show(getApplicationContext(),
"6秒后延迟添加,刷新adapter"
);
setData();
}
private
void
setData() {
new
Thread(
new
Runnable() {
@Override
public
void
run() {
try
{
Thread.sleep(
6000
);
}
catch
(InterruptedException e) {
e.printStackTrace();
}
ArrayList<HashMap<String, String>> arrayList=
new
ArrayList<HashMap<String,String>>();
HashMap<String, String> hashMap;
for
(
int
i =
0
; i <
5
; i++) {
hashMap =
new
HashMap<String, String>();
if
(i %
4
==
0
) {
hashMap.put(
"name"
,
"大海"
);
hashMap.put(
"address"
,
"上海"
);
}
else
if
(i %
4
==
1
) {
hashMap.put(
"name"
,
"老马"
);
hashMap.put(
"address"
,
"深圳"
);
}
else
if
(i %
4
==
2
) {
hashMap.put(
"name"
,
"小三"
);
hashMap.put(
"address"
,
"东莞"
);
}
else
if
(i %
4
==
3
) {
hashMap.put(
"name"
,
"老哥"
);
hashMap.put(
"address"
,
"北京"
);
}
arrayList.add(hashMap);
}
adapter.setAddList(arrayList);
handler.sendEmptyMessage(
1
);
}
}).start();
}
Handler handler =
new
Handler(){
public
void
handleMessage(android.os.Message msg) {
adapter.notifyDataSetChanged();
ToastUtils.show(getApplicationContext(),
"adapter共有"
+adapter.getAllList().size()+
"个数据。"
);
};
};
private
void
initData() {
ArrayList<HashMap<String, String>> arrayList=
new
ArrayList<HashMap<String,String>>();
HashMap<String, String> hashMap;
for
(
int
i =
0
; i <
15
; i++) {
hashMap =
new
HashMap<String, String>();
if
(i %
4
==
0
) {
hashMap.put(
"name"
,
"小明"
);
hashMap.put(
"address"
,
"上海"
);
}
else
if
(i %
4
==
1
) {
hashMap.put(
"name"
,
"老马"
);
hashMap.put(
"address"
,
"深圳"
);
}
else
if
(i %
4
==
2
) {
hashMap.put(
"name"
,
"小三"
);
hashMap.put(
"address"
,
"东莞"
);
}
else
if
(i %
4
==
3
) {
hashMap.put(
"name"
,
"老哥"
);
hashMap.put(
"address"
,
"北京"
);
}
arrayList.add(hashMap);
}
adapter.setAddList(arrayList);
}
}