Search code examples
javaandroidandroid-layoutsharedpreferences

How to add value for android drawable file for button stored in a varible programatically?


I wish to dynamically change image of the button right using below method and it works as it is.

<Button
    android:id="@+id/buttonIdDoesntMatter"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:text="buttonName"
    android:drawableLeft="@drawable/frog"
    android:onClick="listener"
    android:layout_width="fill_parent">
</Button>

Below mehtod of retrieving button image works for me, where frog is the image name.

button.setCompoundDrawablesWithIntrinsicBounds( 0, 0, R.drawable.frog,0);

But i am trying to retrieve the image based on the options accepted by user using shared preference. so i am storing each icon name as value in key value form and retrieve the value of each key selected by user and passing them to drawable as file name.

 <string-array name="pref_icon_title">

        <item>camel</item>
        <item>forg</item>
  </string-array>
  

// value correspond to original image name

    </string-array>
    <string-array name="pref_icon_values">
        <item>camel</item>
        <item>forg</item>
      
        <item></item>
    </string-array>

on retrieving the value selected by user and passing them to the drawable , it gives error and do not know how to pass .. i am using String.valueOf(variable), which doesnt works

on passing the retrieved varaible with String.valueOf is not accepted. Any suggestion would be highly appreciated.

button.setCompoundDrawablesWithIntrinsicBounds( 0, 0, R.drawable.String.valueOf(variable),0);

Solution

  • If I understood well, you're trying to get the drawable's id by the name ?

    You can achieve this using the Resource class, especially the getIdentifier function (it will return a resource identifier for the given resource name)

    Usage

    public int getIdentifier (String name, 
                              String defType, 
                              String defPackage)
    

    So in your case, you should have something like :

    int resourceID = getResources().getIdentifier(
        variable,
        "drawable",
        getPackageName()
    );
    button.setCompoundDrawablesWithIntrinsicBounds( 0, 0, resourceID, 0);
    
    

    If you're not in any activity then you must pass a context instead of resources as parameter then do this

    int resourceID = context.getResources().getIdentifier(
        variable,
        "drawable",
        context.getPackageName()
    );
    button.setCompoundDrawablesWithIntrinsicBounds( 0, 0, resourceID, 0);
    
    

    Note that getIdentifier() Returns 0 if no such resource was found. (0 is not a valid resource ID.)