1. Are you ready for the Galaxy S20? Here is everything we know so far!

Cannot set Button background color in Android Studio

Discussion in 'Android Development' started by brentc, Jan 15, 2022.

  1. brentc

    brentc Newbie
    Thread Starter

    Can't change the button background and onClick to execute the Java code doesn't work
     



    1. Download the Forums for Android™ app!


      Download

       
  2. brentc

    brentc Newbie
    Thread Starter

    I got the onClick to work. I didn't have the word android: to the left of onClick - silly me.

    But I still can't change the background color.
     
  3. GameTheory

    GameTheory Android Expert

    Using onClick in xml has been deprecated. You should be creating your buttons in Java. Something like this in your onCreate.
    Code (Java):
    1. Button btn = findViewById(R.id.myBtn);
    2. btn.setOnClickListener(new View.OnClickListener() {
    3.     @Override
    4.     public void onClick(View v) {
    5.         // do some stuff
    6.     }
    7. });
    Add the id to your button xml layout instead of having onClick.
    Code (XML):
    1. android:id="@+id/myBtn"
    As for the background color, I don't remember too well since I replaced buttons with the CardView which allows you to do fancier stuff.

    In CardView you choose your background like so.
    Code (XML):
    1. card_view:cardBackgroundColor="?attr/colorPrimary"
    or...
    Code (XML):
    1. card_view:cardBackgroundColor="#FFFFFF"
    So with Buttons it should be something similar.
    Code (XML):
    1. android:BackgroundColor="?attr/colorPrimary"
    or...
    Code (XML):
    1. android:BackgroundColor="#FFFFFF"
    Cheers.
     
  4. brentc

    brentc Newbie
    Thread Starter

    The XML is

    android:backgroundTint="#FF00FF"
     
Loading...

Share This Page

Loading...