【问题标题】:Changing background colour of listview item on click - and remembering it单击时更改列表视图项目的背景颜色 - 并记住它
【发布时间】:2019-08-08 06:57:24
【问题描述】:

我正在使用 ArrayList 中的字符串填充列表视图。 单击列表视图项时,我想将背景颜色更改为绿色。 第一个问题,因为我无法更改被点击的项目。

点击一个项目后,我将它的索引添加到用户选择的项目列表中,当第一次加载列表视图时,我需要它来设置所有已选择的列表视图项目的背景颜色为绿色. 问题编号 2 - 我一直在尝试使用 for 循环执行此操作,但不知道如何引用列表视图中的特定项目来设置背景颜色!

基本上,我认为如果有人可以帮助我更改所选列表视图项的颜色,我应该能够做同样的事情,但在循环中保存所有 userFoodPref?

    animalsNameList = new ArrayList<String>();
    userFoodPref = new ArrayList<Integer>();
    getUserSelection();
    getAnimalNames();
    // Create The Adapter with passing ArrayList as 3rd parameter
    ArrayAdapter<String> arrayAdapter =
            new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, animalsNameList);
    // Set The Adapter
    animalList.setAdapter(arrayAdapter);




    // register onClickListener to handle click events on each item
    animalList.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        // argument position gives the index of item which is clicked
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            if(userFoodPref.contains(i)
            ){
                userFoodPref.remove(i);}
                else {
                userFoodPref.add(i);
                View item = animalList.getSelectedView();
                item.setBackgroundColor(0x0000FF00);
            }

            String selectedAnimal=animalsNameList.get(i);
            Toast.makeText(getApplicationContext(), "Animal Selected : "+selectedAnimal,   Toast.LENGTH_LONG).show();
        }
    });
}

【问题讨论】:

  • 那么,它对你有用吗?

标签: android listview


【解决方案1】:

如果我理解得很好,问题是当您设置项目的背景,然后例如滚动列表并返回到上一个位置时,它不记得这个特定项目的背景是绿色的。

我遇到过这个问题并很容易解决:

为您的姓名和布尔值(true = 绿色,false = 非绿色)创建一个列表,并为其创建一个适配器并简单地添加 if (list.get(position).getBoolean) { Currentitem.setBackgroundColor(0x0000FF00)}

当你点击一个项目时,只需将项目位置的布尔值设置为 true 并调用 notifydatasetchanged()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-20
    • 2015-01-13
    • 1970-01-01
    • 2016-01-15
    相关资源
    最近更新 更多