androidcodes androidcodes - 3 months ago 23
Android Question

change color of button when list item is selected

i'm working on a listview in an activity and i want when ever i longpressed any listitem the Button on the action bar changes its color like as get highlihted as suppose " i select
list item the button on the action bar changes from white to gray"
.

listView.setOnItemLongClickListener(new OnItemLongClickListener() {

@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// changes the color button ;
return false;
}
});


or is there any other way that i can do this.

I dont have enough reputation to post a pictures Firstly it looks like Before selecting any item and its looks like thisWhen item is long pressed or selected hope you understand my probleum ,
Thanks in advance

Answer

Edit: as misunderstood original question:

int mPosition = -1;   

lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

    public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int pos, long id) {

        if(mPosition!=-1) {
            //reset color of previously pressed item to white
            lv.getChildAt(mPosition).setBackgroundColor(Color.WHITE);
        }
        //set current item to fray.
        lv.getChildAt(pos).setBackgroundColor(Color.GRAY);
        //put value of currently selected item to mPosition.
        mPosition = pos;

        return true;
    }
});

Old answer below:

Add this into your method.

Button button1 = (Button)findViewById(R.id.button1);
if(this condition){
    button1.setBackgroundColor(Color.GRAY);
}else{
    //whatever.. 
}

This answer covers the same principle, but in more detail using the resources.