0

我正在为历史课编写一个国家/首都抽认卡应用程序。如果我单击按钮,它会变为大写字母,当我向下滚动然后向上滚动时,它会恢复到状态。我怎样才能阻止这种情况发生?这是我的代码:

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]);
        }
    }
}
4

2 回答 2

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();
于 2013-11-05T00:11:36.727 回答
0

我对android还很陌生,不确定这是否是解决这个问题的标准方法,但我已经通过将元素的选定状态存储在一个字段中来解决这个问题。当你滚动时,检查你的按钮的状态,如果它应该被选中,执行你想要的任何操作(突出显示它,改变它的文本,点击它等等)

于 2013-11-04T23:45:50.830 回答