user2960998 user2960998 - 4 months ago 34
Android Question

Android Set button color on first click, unset on second click

please i need help on this.
I have searched here but the answers i have seen are not working for me, the posts being old, the functions are mostly deprecated.

I am trying to set the color of buttons on a single click in order to highlight them and unset the color on a second click. It's like making some choice from a number of buttons, and if I click on a selected button again maybe after changing my mind on my selection, the color should revert to the default. So that i am only left with the selected buttons highlighted.
The buttons are generated with an adapter in gridview and the onclicklistener applies to all of them.
The code i'm using is as shown:

public class ButtonAdapter extends BaseAdapter {
private Context context;

public View getView(int position, View convertView, ViewGroup parent)

{
final Button btn;
if (convertView == null) {

btn = new Button(context);
btn.setLayoutParams(new GridView.LayoutParams(40, 40));
btn.setPadding(2, 2, 2, 2);
}
else {
btn = (Button) convertView;
}
//exus

btn.setText(Integer.toString(gridNumbers[position]));

btn.setTextColor(Color.BLACK);
btn.setId(position);
btn.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//btn.setBackgroundColor(Color.GREEN);
//Toast.makeText(getBaseContext(), "Button clicked", Toast.LENGTH_LONG).show();

if (v.getSolidColor()!=Color.GREEN)
{
btn.setBackgroundColor(Color.GREEN);

}
else
{
btn.setBackgroundColor(Color.GRAY);
}

}
});

return btn;
}
}
}


My XML:

<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="8"
android:columnWidth="20dp"
android:stretchMode="columnWidth"
android:gravity="center" />

Answer

View reused in GridView. So, you should define state for your buttons in your base adapters.

Take an ArrayList that will hold your selected index and remove it when grid is not selected.

Ex:

ArrayList<Integer> selectedItems;

In Construtor

selectedItems = new ArrayList<Integer>();

In OnClickListener

public void onClick(View v) {
if (selectedItems.contains(new Integer(position))) {
     selectedItems.remove(new Integer(position));
     notifyDataSetChanged();    
} else {
    selectedItems.add(new Integer(position));
    notifyDataSetChanged();
}
}

In getView():

if (selectedItems.contains(new Integer(position))) {
         btn.setBackgroundColor(Color.GREEN);    
    } else {
        btn.setBackgroundColor(Color.GRAY); 
    }
Comments