简体   繁体   中英

Change background color to item range of ListView

I have this particular need:

When I click on a Button , some items of my ListView should be highlighted - usually one line or a range of lines, not random elements - by changing the background color. Does android offer such feature? I was thinking to add a method in my custom adapter to set a line range, then adding a check in getView method to decide if setting standard or highlighted background and finally notify the adapter that the data has changed, but I'm quite sure there's something that allows this without repopulating the whole ListView .

I'm aware of multiple selection, but I think it's quite different, isn't it?

UPDATE: using list.getChildAt(pos).setBackgroundColor(Color.BLUE); I'm getting a NullPointerException because it only contains the visible children, not all the items. Isn't there any alternative solution?

UPDATE2: See my answer.

Use following code to highlight list item when your button is pressed. Put this code on button's onClick event.

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

My solution:

In MyAdapter class:

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

Then wherever I want to highlight some lines:

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

@ Vektor88-请尝试更改一次

 final EditText input = new EditText(CLASSNAME.this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM