1. Download our Official Android App: Forums for Android!

Apps Dynamically setting background in Android Studio app

Discussion in 'Android Development' started by Jorge Maldonado, Apr 26, 2016.

  1. Jorge Maldonado

    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    1
    Joined:
    Apr 26, 2016

    Apr 26, 2016
    1
    0
    5
    Male
    I am new to this forum site and also to Android coding.

    I have several radio buttons in an Android app and I need to display a background for each one of them. I am testing the code below, where "bears" is a "png" image in the "res/drawable" folder, and it works fine.

    Code (Java):
    1. ((RadioButton) findViewById(R.id.radButton)).setBackgroundResource(R.drawable.bears);
    What I really need is to decide at run-time which image will be used as background so, basically the image name is saved into a variable.

    From all this, I have 2 questions:

    1) How can I replace the actual name of the image ("bears" in this case) with a variable that contains its name?

    2) The background image covers all the radio button area, including the button itself. Is there a way to avoid covering the button and display the image only as if it were the text of the radio button?

    Respectfully,
    Jorge Maldonado
     

    Advertisement

  2. Unforgiven

    Unforgiven OK Google
    Moderator
    Rank:
     #1
    Points:
    4,238
    Posts:
    35,932
    Joined:
    Jun 23, 2010

    Jun 23, 2010
    35,932
    41,324
    4,238
    Male
    Douglas, MA
    Application Development thread moved to the Development forum for better exposure.:)
     
  3. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #11
    Points:
    1,988
    Posts:
    7,311
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    7,311
    10,431
    1,988
    Male
    Software developer
    South West of England
    1. setBackgroundResource takes an int parameter, so you can declare a variable and assign it an appropriate value

    Code (Text):
    1.  
    2. int backgroundImageId;
    3. ...
    4. // Assign value
    5. backgroundImageId = R.drawable.bears;
    6. ...
    7. // Use it
    8. ((RadioButton) findViewById(R.id.radButton)).setBackgroundResource(backgroundImageId);
    9.  
     
    Unforgiven likes this.
  4. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #11
    Points:
    1,988
    Posts:
    7,311
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    7,311
    10,431
    1,988
    Male
    Software developer
    South West of England
    For 2. you can use a custom radio button image. Is this what you want to achieve?

    radio_button.jpg
     

Share This Page

Loading...