javaandroidandroid-layoutandroid-2.2-froyo

How to programmatically set drawableLeft on Android button?


I'm dynamically creating buttons. I styled them using XML first, and I'm trying to take the XML below and make it programattic.

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

This is what I have so far. I can do everything but the drawable.

linear = (LinearLayout) findViewById(R.id.LinearView);
Button button = new Button(this);
button.setText("Button");
button.setOnClickListener(listener);
button.setLayoutParams(
    new LayoutParams(
        android.view.ViewGroup.LayoutParams.FILL_PARENT,         
        android.view.ViewGroup.LayoutParams.WRAP_CONTENT
    )
);      

linear.addView(button);

Solution

  • You can use the setCompoundDrawables method to do this. See the example here. I used this without using the setBounds and it worked. You can try either way.

    UPDATE: Copying the code here incase the link goes down

    Drawable img = getContext().getResources().getDrawable(R.drawable.smiley);
    img.setBounds(0, 0, 60, 60);
    txtVw.setCompoundDrawables(img, null, null, null);
    

    or

    Drawable img = getContext().getResources().getDrawable(R.drawable.smiley);
    txtVw.setCompoundDrawablesWithIntrinsicBounds(img, null, null, null);
    

    or

    txtVw.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);