簡體   English   中英

從SparseArray填充ListView

[英]Fill ListView from SparseArray

我是列表視圖和數組概念的新手。 我基本上有一個名為shop.Clothes的SparseArray。 我基本上想用shop.Clothes元素填充listView。 為了做到這一點,我理解我必須創建一個ArrayAdapter並將適配器的參數傳遞給listview。 之后,我必須檢查shop.clothes是否包含一個值,如果包含,則必須將其添加到listView。

Java:

ListView listView = (ListView)v.findViewById(R.id.list);
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,R.layout.redeem_shop_list , shop.Clothes);
    listView.setAdapter(arrayAdapter);

    int key = 0;
    for (int i = 0; i < shop.Clothes.size(); i++) {
        key = shop.Clothes.keyAt(i);
        Object value = shop.Clothes.valueAt(i);
        value.toString();

        if(i==0){
            listView.add((String) value);
        }
    }

XML:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<ListView
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

</LinearLayout>

看來我做錯了,我得到這些錯誤:

Cannot resolve constructor ArrayAdapter(SearchableShopList, int, android.util.SparseArray<java.lang.string>)

Cannot resolve method 'add(java.lang.String)'

有人可以在正確的道路上幫助我嗎?

我以非常簡單的方式解決了這個問題。 我沒有為SparseArray創建自定義適配器,而是將SparseArray的值傳遞給了另一個數組,就成功了!

ListView listView = (ListView)v.findViewById(R.id.list);
ArrayList<String> mylist = new ArrayList<String>();

    int key = 0;
    for (int i = 0; i < shop.Clothes.size(); i++) {
        key = shop.Clothes.keyAt(i);
        Object value = shop.Clothes.valueAt(i);
        value.toString();
        mylist.add((String) value);
    }

    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, mylist );
    listView.setAdapter(arrayAdapter);

暫無
暫無

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

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