• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Dynamically setting background in Android Studio app

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.

Java:
((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
 
1. setBackgroundResource takes an int parameter, so you can declare a variable and assign it an appropriate value

Code:
int backgroundImageId;
...
// Assign value
backgroundImageId = R.drawable.bears;
...
// Use it
((RadioButton) findViewById(R.id.radButton)).setBackgroundResource(backgroundImageId);
 
For 2. you can use a custom radio button image. Is this what you want to achieve?

radio_button.jpg
 
Back
Top Bottom