我为历史课写了一个国家/首都flashcard应用程序。如果我单击按钮,它会更改为大写,当我向下滚动,然后向上滚动,它将恢复到该状态。我怎么能阻止这种情况发生?这是我的代码:
package com.example.hostoryflashcards;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class EastEurope extends ListActivity {
String capital[] = {
"Albainia", "Belarus", "Bosina and Herzegouina", "Bulgaria",
"Croatia", "Czech Republic", "Estonia", "Finland", "Greece",
"Hungary", "Kosovo", "Latvia", "Lithuania", "Macedonia", "Molova",
"Montenegro", "Poland", "Romainia", "Russia", "Serbia", "Slovakia",
"Ukraine", "RELOAD"
};
String answer[] = {
"TIRANA", "MINSKA", "SARAJERO", "SOFIA", "ZAGREB", "PRAUGE",
"TALLINN", "HELSINKI", "ATHENS", "BUDAPEST", "PRISTINA", "RIGA",
"VILNIUS", "SKOPJE", "CHISINAU", "PODGORICA", "WARSAW", "BUCHAREST",
"MOSCOW", "BELGRADE", "BRATISLAVA", "LJUBLJANA", "KIEV"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadActivity();
}
private void loadActivity() {
setListAdapter(new ArrayAdapter<String>(EastEurope.this, android.R.layout.simple_list_item_1, capital));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
TextView ov;
ov = (TextView) v;
if (ov.getText().toString() == answer[position]) {
ov.setText(capital[position]);
} else {
ov.setText(answer[position]);
}
}
}
答案 0 :(得分:1)
您正在更改显示的视图但不更改基础数据的问题。当适配器需要重新创建视图时,它使用未更改的数据。
鉴于此,最好的方法是更改数据并告诉适配器更新,而不是自己更改视图。
添加可更改列表并在适配器中使用它:
ArrayList<String> displayed;
// in loadActivity
displayed = new ArrayList<String>(Arrays.asList(capital));
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, displayed));
然后在单击列表项时更改数据并通知适配器:
// In onListItemClick
if (displayed.get(position).equals(answer[position])) {
displayed.set(position, capital[position]);
} else {
displayed.set(position, answer[position]);
}
((ArrayAdapter) getListAdapter()).notifyDataSetChanged();
答案 1 :(得分:0)
我对android很新,不确定这是否是解决这个问题的标准方法,但我已经通过在元素中存储元素的选定状态来解决这个问题。滚动时,检查按钮的状态以及是否应该选择它,执行您希望的任何操作(突出显示,更改文本,单击等)。