Search code examples
androidbuttongridviewonclickbaseadapter

Changing color of buttons with onclick events


I'm trying to create a Grid with 100 buttons, and a custom color selector. When i click a random button, it should change its' background into the selected color. Unfortunately I'm stuck on the following:

MainActivity: I'm not sure how to automate the onclick event for every button seperately, as the onclick function doesn't recognise which button is clicked in the inner class.

I'm using a gridview with a custom adapter:

Adapter: The adapter implemented in my Gridview --> linearlayout.pixel is the xml file for my button.

Code linearlayout.pixel:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp" >


<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""
    android:background="@drawable/my_button"
    android:id="@+id/grid_button"
    />

code drawable my_button:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="3dp" />
<stroke android:width="5px" android:color="#000000" />

Any suggestions are welcome!


Solution

  • Try this:

    Button button = (Button)findViewById(R.id.grid_button);
    button.setOnClickListener(new View.OnclickListener()
    {
       @Override
       public void onClick(View view){
           button.setBackgroundColor("#4FC3F7");
       }
    };