簡體   English   中英

如何在Android中更新ListView?

[英]How to update ListView in Android?

我想通過單擊具有更新的建築物數量(以及將來的價格)的元素來升級ListView。 現在,該列表僅在重新啟動應用程序時更新。

onCreate:

Building[] buildings = {
                new Building(1, getString(R.string.mouse), 15, iMouses),
                new Building(2, getString(R.string.grandma), 100, iGrandmas),
                new Building(3, getString(R.string.farm), 500, iFarms),
                new Building(4, getString(R.string.factory), 3000, iFactories),
                new Building(5, getString(R.string.mine), 10000, iMines)
        };

        ListView lstBuildings = (ListView)findViewById(R.id.lstBuildings);

        final ArrayAdapter<Building> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, buildings);

        lstBuildings.setAdapter(adapter);

        lstBuildings.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id){
                if (id+1 == 1) { //         Mouse
                    if ((int) fCats >= 15) {
                        fIncome = fIncome + 0.1f;
                        fCats = fCats - 15;
                        iMouses = iMouses + 1;
                        iBuildings = iBuildings + 1;

                        adapter.notifyDataSetChanged();
                    }

我的建築課:

class Building {
    private final int id;
    private final String name;
    private final double price;
    private final int number;

    public Building(int id, String name, double price, int number) {
        super();
        this.id = id;
        this.name = name;
        this.price = price;
        this.number = number;
    }

    @Override
    public String toString() {
        return this.id + ". " + this.name + " [" + (int)this.price + "] (" + this.number + ")";
    }
}

感謝您的幫助,請給我一些優化代碼的技巧。

解決方案非常簡單:

adapter.notifyDataSetChanged()

看這個:

if (id+1 == 1) { //         Mouse
                if ((int) fCats >= 15)
                    fIncome = fIncome + 0.1f;
                    fCats = fCats - 15;
                    iMouses = iMouses + 1;
                    iBuildings = iBuildings + 1;

                    adapter.notifyDataSetChanged();
                }

您只是不更新​​適配器的數據,而只是設置一些變量

首先,我看到您更新了變量iMouses,但是沒有更新以前在建築物中存儲iMouses的位置。 因此建築物數組中的數據未更改。 它必須在數組中更改,因為這就是列表視圖中顯示的內容。

另外,您將需要實現以下代碼來使notifyDataSetChanged起作用。 適配器中的數據與建築物陣列的數據不同。

adapter.clear();
adapter.addAll(buildings);
notifyOnDataSetChanged();

暫無
暫無

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

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