Android Eclipse-当更新Listview时,Listview上的选定项会松开背景色

Android Eclipse-当更新Listview时,Listview上的选定项会松开背景色,android,listview,colors,Android,Listview,Colors,经过几天的反复尝试,我不得不向你寻求帮助 我有一个带有列表视图和一个按钮的活动。当我在Listview上选择一个项目时,颜色会改变。一切都很好。当我按下按钮时,所选项目将更新其值。。这也很好,但listview项中选定的颜色将消失。我希望在使用以下内容更新listview时保持项目的颜色: list.setAdapternew ArrayAdapterthis,android.R.layout.simple_可扩展_列表_项_1,数据 以下是我在该活动中的完整代码: `公共类AllActivit

经过几天的反复尝试,我不得不向你寻求帮助

我有一个带有列表视图和一个按钮的活动。当我在Listview上选择一个项目时,颜色会改变。一切都很好。当我按下按钮时,所选项目将更新其值。。这也很好,但listview项中选定的颜色将消失。我希望在使用以下内容更新listview时保持项目的颜色:

list.setAdapternew ArrayAdapterthis,android.R.layout.simple_可扩展_列表_项_1,数据

以下是我在该活动中的完整代码: `公共类AllActivity扩展了活动{

int i;

ListView list;

ArrayList<String> data;

int index;

int top;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);


setContentView(R.layout.activity_all);

list = (ListView) findViewById(R.id.lv_select2);

DatabaseCounter db = new DatabaseCounter(this);

ArrayList<Counter> counterList = db.getAllCounters();

data = new ArrayList<String>();

for (Counter counter : counterList){

    data.add(counter.getCounterName() + " : " + String.valueOf(counter.getCount()));

}

list.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,data));

list.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
        // TODO Auto-generated method stub

        i = Integer.parseInt(String.valueOf(id));

        index = list.getFirstVisiblePosition();

        View v = list.getChildAt(0);

        top = (v == null) ? 0 : v.getTop();


        for (int j = 0; j < parent.getChildCount(); j++)

            parent.getChildAt(j).setBackgroundColor(Color.TRANSPARENT);


            view.setBackgroundColor(Color.MAGENTA);


    }

});
}

}
`

如果您希望列表项视图具有永久性颜色,那么您不仅应该在单击时输入该颜色,还应该告诉适配器此项应具有该颜色。当用户滚动列表视图时,列表视图将消失。当视图返回时,颜色已消失。您必须在getView中再次设置颜色。为此,您必须向适配器添加另一种颜色或布尔数组。在onclick中,为该位置上的项目设置正确的值。

当我在列表视图中选择一个项目时,颜色会改变?你的意思是当我点击列表视图上的一个项目时,我会改变颜色吗?但是从listview项目中选择的颜色显示为Ok。但是你忘了告诉我什么时候。
public void onButtonClick(View v) {
    // TODO Auto-generated method stub
    DatabaseCounter db = new DatabaseCounter(this);


    Counter counter;

    switch(v.getId()){


    case R.id.btn2_plus:


        counter = db.getCounter(i+1);

        counter.setCount(counter.getCount()+counter.getIncValue());

        db.updateCounter(counter);

        data.set(i, counter.getCounterName() + " : " + String.valueOf(counter.getCount()));

        list.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,data));

        list.getChildAt(0).setBackgroundColor(Color.MAGENTA);

        list.setSelectionFromTop(index, top);



        break;

    }
}