Serephucus
Serephucus

Reputation: 3

ImageButton background color change onClick

First-time Android dev, though have used C# and Java in the past.

Trying to make a simple, Windows 8-like GUI. At the moment I have one tile (ImageButton) with a background color set in activity_main.xml.

    <ImageButton
    android:id="@+id/btn1"
    android:layout_width="120dp"
    android:layout_height="120dp"
    android:background="#FF0000"
    android:onClick="changeColor"/>

And I have a function to change the color in MainActivity.java.

public void changeColor(){
    ImageButton btn1 = (ImageButton) findViewById(R.id.btn1);
    btn1.setBackgroundColor(Color.GREEN);
}

Compiles fine, but every time I click the red square, the app crashes.

I'm assuming there's something fundemental about how Android is developed that I'm missing which is leading to a very obvious mistake. Is there a better way to be doing this rather than ImageButtons?

Thanks!

Upvotes: 0

Views: 8248

Answers (3)

Mdlc
Mdlc

Reputation: 7288

Is there a better way to be doing this rather than ImageButtons?
Yes, ImageButtons are mainly for creating a 'clickable' image. If you simply want a colored button, a regular Button will do fine.

You can do this by setting your Buttons background right from XML using a selector with a Drawable state list.

A good example can be found here: https://stackoverflow.com/a/3882151/1683141 (a color will also qualify as a Drawable)

Why isn't my current code working?
You should add the view as parameter to your method like this:

public void changeColor(View view){
   view.setBackgroundColor(Color.GREEN);
}

Upvotes: 0

Valentin Baryshev
Valentin Baryshev

Reputation: 2205

It's better to create a selector and set it as backgraund to the button.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/button_pressed" />
    <item android:color="@color/button_normal" />
</selector>

Hope it'll help you. P.S. useful link

Upvotes: 2

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132972

Compiles fine, but every time I click the red square, the app crashes.

Because when adding android:onClick in xml then method must be public and accept a View as its only parameter which we want to call on View click:

public void changeColor(View view){
   ImageButton btn1 = (ImageButton) findViewById(R.id.btn1);
   btn1.setBackgroundColor(Color.GREEN);
}

Upvotes: 3

Related Questions