Andreea
Andreea

Reputation: 151

How can I set a background image for a button from ..Activity.java, in android?

I wrote the following code:

            ImageButton b = (ImageButton) v;  
                b.setBackgroundResource(R.drawable.tom);  

tom.png is in res/drawable. The code above it's working, but I saved the image name in the database (for example "tom"). And I tried the code behind:

    InfoDataSource datasourceRuta = new InfoDataSource(this);
    datasourceRuta.open();

    String strInfo = "";        


    List<Info> objInfo = datasourceRuta.GetInfo()

    for (Info info : objInfo) {
        strInfo = info.getImg0();

            ImageButton b = (ImageButton) v;  
                b.setBackgroundResource(R.drawable.strInfo);  

        } 

strInfo = "tom", and I get an error: strInfo cannot be resolved or is not a field. Do you have a solution for me? Should I save the image in database?

Upvotes: 1

Views: 752

Answers (1)

vanloi999
vanloi999

Reputation: 485

When you copy "tom" image to drawable folder, Android generates a field in gen/R.java a tom field for that. In this case. There is no strInfo in R.java, so you can't access it.

In this case, you should read from image file, create a Bitmap and setBackground for your button. You can take this for reference: How to read a file into a Java Bitmap?

Upvotes: 2

Related Questions