user2960998
user2960998

Reputation: 17

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" />

Upvotes: 0

Views: 3302

Answers (4)

Aditya Vyas-Lakhan
Aditya Vyas-Lakhan

Reputation: 13555

I tried this way and it worked for me,if you want to change on click

counter = 1;
        //By Default set color
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (counter == 1)
                {
                   // Default color
                    counter = 2;
                }
                else
                {
                    //your color
                    counter = 1;
                }
            }
        });

Upvotes: 1

STNHZ
STNHZ

Reputation: 23

You can use a list of boolean properties instead of doing this. Set a public boolean list in your class (it should be public and outside of any functions otherwise the onclicklistener will have error)

List<boolean> blist=new Arraylist<boolean>(Size);

//Size is maximum number of buttons

int index;

Then whenever you create a new button add this:

blist.add(index,false);
index++;

in the onclicklistener; find the index of the button from its position and save the index in an integer named pos.

if(blist.get(pos)==false)
{
 //not clicked yet
 blist.remove(pos);
blist.add(pos,true);
//here write the code u need for this if
}
else
{
blist.remove(pos);
blist.add(pos,false);
//todo: ur code for else
}

Upvotes: 1

Chirag Jain
Chirag Jain

Reputation: 1612

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

Upvotes: 0

Kushal Sharma
Kushal Sharma

Reputation: 5973

Use toggle button insted of normal button. Like

<ToggleButton 
        android:id="@+id/toggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/check"   //check.xml
        android:layout_margin="10dp"
        android:textOn=""
        android:textOff=""
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:layout_centerVertical="true"/>

and then make an xml file check.xml in drawable folder something like

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/selected_image"
          android:state_checked="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/unselected_image"
        android:state_checked="false"/>

</selector>

refrence.

Upvotes: 0

Related Questions