您不需要编写自定义 ListView。您应该使用个性化布局和自定义适配器。
首先,编写一个布局来定义每一行的外观。这是一个基本示例:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp" />
<TextView
android:id="@+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp" />
<TextView
android:id="@+id/link"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp" />
</LinearLayout>
(将其保存list_item.xml
在您的res/layout
文件夹中。)
接下来,我建议您创建一个自定义适配器以有效地显示您的布局:
public class ItemAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<Item> objects;
public ItemAdapter(Context context, List<Item> objects) {
this.objects = objects;
inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.list_item, parent, false);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.title);
// Do the same for description and link
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
Item item = objects.get(position);
holder.title.setText(item.getTitle());
// Same for description and link
return convertView;
}
// Override the other required methods for BaseAdapter
public class ViewHolder {
TextView title;
TextView description;
TextView link;
}
}
要了解有关自定义适配器、ViewHolders 和效率的更多信息,请观看 Android 的 Romain Guy关于此主题的演讲。
希望有帮助!