如何更改由选项限制的列表视图中项目的背景颜色

时间:2015-11-03 14:31:23

标签: android

我有我的代码:

AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String elementoSeleccionado = parent.getItemAtPosition(position).toString();
        Boolean realizado = getRealizadoPorElemento(elementoSeleccionado);
        if (realizado == true){
            actualizaRealizado(elementoSeleccionado,"N");
            elementosList.getChildAt(position).setBackgroundColor(Color.TRANSPARENT);
        } else if (realizado == false){
            actualizaRealizado(elementoSeleccionado,"S");
            elementosList.getChildAt(position).setBackgroundColor(Color.parseColor("#3DF400"));
        }
    }
};

这仍然有效,但问题出在这里。

我有一个方法运行列表视图并用其他颜色更新一些:

ArrayList<String> elementos = LeerElementosLista();
if (elementos.isEmpty() == false) {
    ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, LeerElementosLista());
    elementosList.setAdapter(arrayAdapter);
    Boolean realizadoelem = false;
    int count = elementosList.getCount();

    for (int i = 0; i < count; i++){
        String elem = elementosList.getItemAtPosition(i).toString();
        realizadoelem = getRealizadoPorElemento(elem);

        if (realizadoelem == true){
            elementosList.getChildAt(i).setBackgroundColor(Color.parseColor("#3DF400"));
        }
    }
} else {
    //Toast.makeText(this, "No hay Listas para mostrar!!!", Toast.LENGTH_SHORT);
}

第二种方法就是这一行

elementosList.getChildAt(i).setBackgroundColor(Color.parseColor("#3DF400"));

无效,应用关闭,但我在控制台中没有错误。

2 个答案:

答案 0 :(得分:1)

这不是这样做的方式。

您需要从BaseAdapter类创建自定义适配器。

在那里,您可以在getView()方法上设置单元格的背景颜色。

希望这有帮助。

答案 1 :(得分:0)

也许你需要设置drawable / selector而不是color.If你覆盖默认背景它aloso删除默认选择器。所以你的列表是用一个选择器创建的,你正在尝试改变它。可能这里是冲突。

但是更好地提供logcat输出。它会更容易;

相关问题