Vektor88
Vektor88

Reputation: 4920

Change background color to item range of ListView

I have this particular need:

When I click on a Button, some items of my ListViewshould 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 NullPointerExceptionbecause it only contains the visible children, not all the items. Isn't there any alternative solution?

UPDATE2: See my answer.

Upvotes: 0

Views: 1097

Answers (3)

Vektor88
Vektor88

Reputation: 4920

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

Upvotes: 1

Appoorva Faldu
Appoorva Faldu

Reputation: 444

@Vektor88 - Please try change once

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

Upvotes: -1

Jitesh Dalsaniya
Jitesh Dalsaniya

Reputation: 1917

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

Upvotes: 1

Related Questions