簡體   English   中英

如何在Android中的10行列表視圖中添加例如5個元素?

[英]How to add e.g. 5 elements to a 10 rows listview in android?

我以前在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]);
            }

前五行和其他一些行也設置了圖像,這是為什么以及如何解決呢? 謝謝

一般來說

由於要在列表中顯示Data ,因此請創建一個代表數據的對象。

就像您在上面的評論中命名的一樣:

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 <ListEntry>)訪問所有數據。 這樣,您就可以繞開indexOutOfBoundsException。

查找任何listadapter在線教程,例如,從一個Vogella

為什么有超過前五個條目的圖像?

用於列表視圖的Android適配器實現了一種緩存機制,以將新列表項(例如行)的膨脹(性能/內存成本密集型)降低到最小。 因此,創建的行數(或更多)僅與列表顯示的一樣。 由於您僅設置圖像(如果有的話),但從未從行中刪除已設置的圖像,因此會導致某些行重播不應播放的圖像。 這些行是從先前展開的行中緩存的。

因此添加類似

if (listItem.photo != null) {
  image.setImageResource(images[arg0]);
} else {
  image.setVisibility(View.GONE);
}

作為listview及其緩存機制的參考,請參閱ListViews上的Romain Guy。

編輯有關Listadapter的用法

上面發布的getView(..)ListAdapter實現內部,很可能是擴展了ArrayAdapter<T> 如果是這樣,您的T現在應該聲明ListEntry並且您有任何代碼行指出

MyArrayAdapter myAdapter = new MyArrayAdapter()或類似的東西。

現在您有一個數組或ListEntry的列表,如List<ListEntry> myCollection = new ArrayList<ListEntry>()ListEntry[] listEntries = new ListEntry[10]並使用

myAdapter.addAll(listEntries);

要在getView(..)內獲取列表項,可以使用:

ListEntry currentEntry = getItem(arg0);

並引用currentEntry的單個成員進行設置;-)

關於什么

if (images[arg0] != null) image.setImageResource(images[arg0]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM