list.xml
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
item.xml
<TextView
android:id="@+id/name"
android:layout_width="100dp"
android:layout_height="match_parent"
app:layout_constraintRight_toLeftOf="@+id/price"/>
<TextView
android:id="@+id/price"
android:layout_width="100dp"
android:layout_height="match_parent"
app:layout_constraintLeft_toRightOf="@+id/name"/>
Book.java
public class Book {
private String bookName;
private String bookPrice;
public Book(String bookName, String bookPrice) {
this.bookName = bookName;
this.bookPrice = bookPrice;
}
public String getBookName() {
return bookName;
}
public String getBookPrice() {
return bookPrice;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public void setBookPrice(String bookPrice) {
this.bookPrice = bookPrice;
}
}
list.java
List<Book> data = new ArrayList<>();
for(int i = 0; i < 3; i++) {
Book b = new Book("book","100");
data.add(b);
}
ListView listview = (ListView) findViewById(R.id.listview);
MyListViewAdapter t = new MyListViewAdapter(this, data);
listview.setAdapter(t);
MyListViewAdapter.java
public class MyListViewAdapter extends BaseAdapter {
private List<Book> list;
LayoutInflater inflater;
public MyListViewAdapter(Context context, List<Book> list) {
this.list = list;
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
if (list == null) {
return 0;
}
return list.size();
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public Object getItem(int i) {
if (list == null) {
return null;
}
return list.get(i);
}
@Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
ViewHolder viewHolder;
// 当view为空时才加载布局,否则,直接修改内容
if (convertView == null) {
// 通过inflate的方法加载布局,context需要在使用这个Adapter的Activity中传入。
convertView = inflater.inflate(R.layout.item, null);
viewHolder = new ViewHolder();
viewHolder.bookName = (TextView) convertView.findViewById(R.id.name);
viewHolder.bookPrice = (TextView) convertView.findViewById(R.id.price);
convertView.setTag(viewHolder); // 用setTag方法将处理好的viewHolder放入view中
} else { // 否则,让convertView等于view,然后从中取出ViewHolder即可
viewHolder = (ViewHolder) convertView.getTag();
}
// 从viewHolder中取出对应的对象,然后赋值给他们
viewHolder.bookName.setText(list.get(i).getBookName());
viewHolder.bookPrice.setText(list.get(i).getBookPrice());
// 将这个处理好的view返回
return convertView;
}
private class ViewHolder {
public TextView bookName;
public TextView bookPrice;
}
}