gpt4 book ai didi

java - Android中如何更新ListView?

转载 作者:行者123 更新时间:2023-12-02 05:00:58 24 4
gpt4 key购买 nike

我想通过点击其元素来升级我的 ListView,并更新建筑物数量(以及 future 的价格)。现在,该列表仅在应用程序重新启动时更新。

创建时:

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();
}

您根本没有更新适配器的数据,您只是设置一些变量

关于java - Android中如何更新ListView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28286427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com