ListView适配器
ArrayAdapter的使用方法
- 设置数据源
String[]strings={"darcygail","abigail","cj","vivian"};
- 初始化ArrayAdapter
arrayAdapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,strings);
- 加载数据
listView.setAdapter(arrayAdapter);
simpleAdapter使用方法
- 数据源
- 初始化SimpleAdapter
- 第一个为上下文
- 第二个为数据源
- 第三个为布局文件
- 第四个为数据源中对应项(Map的键名
- 第五个为布局文件中对应项
simpleAdapter = new SimpleAdapter(this,getData(),R.layout.item,new String[]{"pic","text1","text2"},new int[]{R.id.iv,R.id.tv1,R.id.tv2});
----------
private List<Map<String, Object>> getData(){
System.out.println(dataList);
for(int i=0;i<14;i++){
Map<String, Object> map = new HashMap<String, Object>();
map.put("pic",R.mipmap.ic_launcher);
map.put("text1","Darcy"+i);
map.put("text2","abigail"+i);
dataList.add(map);
Log.i("Test", dataList.toString());
}
return dataList;
}
- 加载,同arrayAdapter。
- 布局文件如下:
<?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">
<ImageView
android:id="@+id/iv"
android:src="@mipmap/ic_launcher"
android:layout_marginLeft="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<LinearLayout
android:layout_width="wrap_content"
android:orientation="vertical"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv1"
android:textSize="20sp"
android:textColor="#b11010"
android:text="Darcy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/tv2"
android:textSize="16sp"
android:textColor="#00dd00"
android:text="darcygail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="删除"
android:layout_marginLeft="120dp"
android:id="@+id/button"/>
</LinearLayout>
ListView监听器
条目点击事件
- 实现方法:
listView.setOnItemClickListener(this);
- Activity实现
AdapterView.OnItemClickListener
接口 - 重写方法:
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String text=listView.getItemAtPosition(position)+"demo";
System.out.println(text);
Toast.makeText(Main.this,"Position is"+position+"Item is "+text,Toast.LENGTH_SHORT).show();
}
滚动监听
- 实现方法:
listView.setOnScrollListener(this);
- Activity实现这个接口:
AbsListView.OnScrollListener
- 重写方法:
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
Log.i("Tag","NOthing");
if(scrollState==SCROLL_STATE_FLING){
Map<String,Object> map=new HashMap<String,Object>();
Toast.makeText(Main.this,"Scrolling",Toast.LENGTH_SHORT).show();
map.put("pic",R.mipmap.ic_launcher);
map.put("text1","New Line");
map.put("text2","demo");
dataList.add(map);
simpleAdapter.notifyDataSetChanged();}
}
ps:这里写了简单的下拉刷新效果:
simpleAdapter.notifyDataSetChanged();
adapter有个方法可以通知数据变更,从而可以自动添加数据到显示界面。