将背景颜色更改为ListView的项目范围

时间:2013-09-24 12:11:40

标签: java android listview android-listview

我有这个特殊需要:

当我点击Button时,我的ListView的某些项目应该突出显示 - 通常是一行或一系列行,而不是随机元素 - 通过更改背景颜色。 android提供这样的功能吗? 我想在我的自定义适配器中添加一个方法来设置行范围,然后添加一个检查getView方法来决定是否设置标准或突出显示的背景,最后通知适配器数据已更改,但我'我确信有一些东西允许这个而不重新填充整个ListView

我知道有多种选择,但我认为这是完全不同的,不是吗?

更新:使用list.getChildAt(pos).setBackgroundColor(Color.BLUE);我收到NullPointerException因为它只包含可见的子项,而不是所有项目。有没有替代解决方案?

UPDATE2:查看我的回答。

3 个答案:

答案 0 :(得分:1)

按下按钮时,使用以下代码突出显示列表项。 将此代码放在按钮的onClick事件上。

listview.getChildAt(position).setBackgroundColor(Color.BLUE);

答案 1 :(得分:1)

我的解决方案:

在MyAdapter类中:

private boolean highlighted = false;
private Integer from, to;
//....
public void setHighlight(int from, int to) {
    if ((this.from != null && this.from == from) && (this.to != null && this.to == to)) {
        highlighted = false;
        this.from = null;
        this.to = null;
    } else {
        highlighted = true;
        this.from = from;
        this.to = to;
    }
}
//...
@Override
public View getView(int pos, View v, ViewGroup vg) { 
    parsedLine entry = lines.get(pos);
    //...
    if (highlighted && pos>=from && pos<=to){
        v.setBackgroundColor(Color.parseColor(Theme.getHighlightColor()));
    } 
    //...
    return v;
}

然后,无论我想在哪里突出显示某些行:

MyAdapter myadapter = (MyAdapter)mylist.getAdapter();
myadapter.setHighlight(from, to);
myadapter.notifyDataSetChanged();
mylist.setSelection(from);

答案 2 :(得分:-1)

@ Vektor88 - 请尝试更改一次

 final EditText input = new EditText(CLASSNAME.this);
相关问题