Android 如何从ArrayList填充ListView<;CustomClass>;?
我正在写一个android RSS阅读器 当我的程序在最后读取提要时,返回一个ArrayList 项目是我的班级:Android 如何从ArrayList填充ListView<;CustomClass>;?,android,android-listview,populate,rss-reader,Android,Android Listview,Populate,Rss Reader,我正在写一个android RSS阅读器 当我的程序在最后读取提要时,返回一个ArrayList 项目是我的班级: public class Item implements Serializable { private String title; private String description; private String link; public Item() { setTitle(null); setDescript
public class Item implements Serializable {
private String title;
private String description;
private String link;
public Item() {
setTitle(null);
setDescription(null);
setLink(null);
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
现在,我如何填充一个自定义列表视图,其中包含3个文本视图,分别用于
标题
、说明
和链接
?您不需要编写自定义列表视图。您应该使用个性化布局和自定义适配器
首先,编写一个布局,定义每行的外观。以下是一个基本示例:
<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>
要了解更多关于自定义适配器、视窗支架和效率的信息,请观看Android的Romain Guy
希望有帮助 我喜欢你的答案,但我认为OP甚至没有尝试阅读任何关于ListView和适配器的教程。@Nikitabloglazov我也有这种感觉。但是有人先在这里给出了一个无用的答案,而且很多搜索引擎教程都很慢(我很恼火),所以我花了10分钟来准备这个答案。此外,我的布局是原始的,有更多的工作要做的一般来说,这留下了更多的OP学习@nikita你知道,我花了两天的时间试图找到一个好的教程,但我所发现的都是错误的。这个:context.getSystemService让我发疯,因为在一个教程中,他们是这样写的:getsystemservices下次你像那样挣扎的时候,请访问并尝试搜索文档中的方法(在这种情况下,
getSystemService
)。这可能会有所帮助。
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;
}
}