效果如下:
1.activity_lv.xml
......
<ListView
android:id="@+id/lv_content"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
.......
2.MainActivity.java
2.1 datas 获取的设置数据
List<MyData> datas = getDatas();
2.2 列表的视图
adapter = new MyAdapter<MyData>(MainActivity.this, datas, R.layout.item) {
@Override
public void convert(ViewHolder holder, MyData item, View convertView, ViewGroup parent, int position) {
holder.setText(R.id.tv1, item.getName1());
holder.setText(R.id.tv2, item.getName2());
}
};
2.2.1 item的视图
<?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="wrap_content"
android:orientation="horizontal"
android:padding="12.0dp">
<ImageView
android:id="@+id/iv_icon"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginRight="5dp"
android:src="@mipmap/ic_launcher" />
<TextView
android:id="@+id/tv1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3.0"
android:textSize="16.0sp" />
<TextView
android:id="@+id/tv2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2.0"
android:gravity="center"
android:textSize="16.0sp" />
<ImageView
android:id="@+id/iv_arrow"
android:layout_width="15.0dip"
android:layout_height="15.0dip"
android:paddingLeft="5.0dp"
android:src="@drawable/ic_arrow_right" />
</LinearLayout>
2.3 item点击事件
private AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
final MyData data = adapter.getItem(position);
Toast.makeText(MainActivity.this, data.getName2(), Toast.LENGTH_SHORT).show();
}
};
2.4 MyData实体类
public class MyData {
private String name1;
private String name2;
public MyData(String name1, String name2) {
this.name1 = name1;
this.name2 = name2;
}
public String getName1() {
return name1;
}
public void setName1(String name1) {
this.name1 = name1;
}
public String getName2() {
return name2;
}
public void setName2(String name2) {
this.name2 = name2;
}
}
2.5 MyAdapter类,获取/添加/清空的数据
......
@Override
public int getCount() {
return datas == null ? 0 : datas.size();
}
public void addDatas(List<T> items) {
if (datas == null) {
datas = new ArrayList<>();
}
if (items != null) {
datas.addAll(items);
}
}
......
public void clearDatas() {
if (datas != null) {
datas.clear();
}
}
}
2.6 ViewHolder.java,设置文本和图片
......
public ViewHolder setText(int id, CharSequence text) {
TextView textView = getView(id);
textView.setText(text);
return this;
}
......
public ViewHolder setImageResource(int id, int resId) {
ImageView imageView = getView(id);
imageView.setImageResource(resId);
return this;
}
......
3.源代码地址下载
点击链接:下载源代码