我以前正在研究PHP和js,最近我正在研究android listview 但是,我在为listview
创建自定义适配器时遇到了问题public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO
if (arg1 == null) {
arg1 = myInflater.inflate(R.layout.grid, arg2, false);
}
TextView name = (TextView) arg1.findViewById(R.id.text1);
TextView desc = (TextView) arg1.findViewById(R.id.text2);
ImageView image = (ImageView) arg1.findViewById(R.id.image1);
if (arg0 < images.length) {
image.setImageResource(images[arg0]);
}
name.setText(names[arg0]);
desc.setText(description[arg0]);
return arg1;
}
问题是我有3个数组内容传递给listview网格,对于前两个数组,有10个元素,最后一个只有5个。所以,它最后一个是不合格的。我添加了一个条件来检查它是否超过5,但args0似乎没有根据行增加?
if (arg0 < images.length) {
image.setImageResource(images[arg0]);
}
前五行和其他一些行也有图像设置,为什么这样以及如何解决这个问题?感谢
答案 0 :(得分:1)
一般
因为要在列表中显示Data
,plx会创建一个表示数据的对象。
就像你上面评论中提到的那样:
public class ListEntry {
String name = "";
String gender = "";//use enum here perhaps -.-
String photoUrl = null; //or use byte[] photo or whatever you've stored in your array before
// write getters/setters for your members
}
然后您可以使用一个数组ListEntry[]
(或List&lt; ListEntry&gt;)来访问所有数据。这样你就可以绕过indexOutOfBoundsException。
在线查找任何listadapter教程,例如来自Vogella
的那个为什么有超过前五个条目的图像?
用于Listviews的Androids适配器实现了一种缓存机制,以将新列表项(例如行)的膨胀(性能/内存成本密集)降至最低。因此,列表显示的行数(或更多)只能创建。因为您只设置图像(如果有),但从不从行中删除已经设置的图像,您将导致某些行重放不应该的图像。这些行是从先前向外滚动的行缓存的。
因此添加类似
的内容if (listItem.photo != null) {
image.setImageResource(images[arg0]);
} else {
image.setVisibility(View.GONE);
}
作为listviews及其缓存机制的参考,请参阅Romain Guy on ListViews
编辑关于Listadapter的使用
您在上面发布的getView(..)
内容位于ListAdapter
实施内容中,您可能已经扩展了ArrayAdapter<T>
。如果是这样,您的T
现在应该说明ListEntry
并且您有任何代码行说明
MyArrayAdapter myAdapter = new MyArrayAdapter()
或类似的东西。
现在你有一个像List<ListEntry> myCollection = new ArrayList<ListEntry>()
或ListEntry[] listEntries = new ListEntry[10]
这样的ListEntry数组或列表并使用
myAdapter.addAll(listEntries);
在您可以使用的getView(..)
中获取列表中的项目:
ListEntry currentEntry = getItem(arg0);
并引用currentEntry的单个成员来设置它们; - )
答案 1 :(得分:0)
怎么样?
if (images[arg0] != null) image.setImageResource(images[arg0]);