Java 如何在Android中更新ListView?
我想用更新的建筑数量(以及未来的价格)来升级我的ListView。现在,该列表仅在应用程序重新启动时更新 一旦创建:Java 如何在Android中更新ListView?,java,android,class,listview,adapter,Java,Android,Class,Listview,Adapter,我想用更新的建筑数量(以及未来的价格)来升级我的ListView。现在,该列表仅在应用程序重新启动时更新 一旦创建: Building[] buildings = { new Building(1, getString(R.string.mouse), 15, iMouses), new Building(2, getString(R.string.grandma), 100, iGrandmas),
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();
}
感谢您的帮助,请为我的代码提供一些优化技巧。解决方案非常简单:
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();
}
您只是没有更新适配器的数据,只是设置了一些变量。首先,我看到您更新了变量iMouse,但没有更新以前存储iMouse的buildings数组中的位置。因此,建筑物阵列中的数据没有更改。它必须在数组中更改,因为这是listview中显示的内容 此外,您还需要实现以下代码才能使notifyDataSetChanged正常工作。适配器中的数据与您的建筑阵列中的数据不同
adapter.clear();
adapter.addAll(buildings);
notifyOnDataSetChanged();
我看不到您正在更新适配器,可能是重复的。如果您没有,则即使您使用
notifyDataSetChanged
@Rohit5k2:它也不会更新,以及如何更新适配器?从您的代码中,我不明白您在单击该项目时试图更新什么。如果没有这一点,我无法告诉您需要做什么。作为旁注,这两行以及随后匹配的缩进if((int)fCats>=15)fIncome=fIncome+0.1f代码>有误导性。我已经安装了适配器。notifyDataSetChanged();在我第一次复制粘贴代码的末尾,它没有工作,我设置:adapter.clear();adapter.addAll(建筑物);adapter.notifyDataSetChanged()代码>但现在当我点击这个选项时,应用程序崩溃了:(logcat说了什么?你也可以在更新建筑物数组后重新创建适配器。然后再次将其分配给列表视图,然后调用notifyDataSetChanged。---adapter=new ArrayAdapter(这个,android.R.layout.simple_list_item_1,建筑物)------lstBuildings.setAdapter(适配器)---adapter.notifyDataSetChanged();
adapter.clear();
adapter.addAll(buildings);
notifyOnDataSetChanged();