Android Eclipse - Listview中的Selected Item在更新Listview时丢失了他的背景颜色

时间:2014-07-09 10:46:52

标签: android listview colors

经过几天的尝试和错误,我得请你帮忙。

我有一个带有Listview和一个Button的Activity。当我在Listview上选择一个项目时,颜色会发生变化。一切都好。当我按下按钮时所选项目更新他的值..也可以正常工作,但列表视图项目中的选定颜色会消失。当我用以下内容更新列表视图时,我希望在项目上保持颜色:

  

“list.setAdapter(new ArrayAdapter(this,android.R.layout.simple_expandable_list_item_1,data));”

以下是该活动的完整代码: `public class AllActivity扩展了Activity {

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


    }

});

}

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;

    }
}

} `

1 个答案:

答案 0 :(得分:0)

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