Reputation: 853
I have a button in a LinearLayout where I assign a drawableLeft in XML like this:
<Button android:id="@+id/button_news"
style="@style/main_button"
android:drawableLeft="@drawable/news"
android:text="@string/button_news" />
This works fine and the button looks like expected.
I want to change the image programmatically to show the number of news available. This is the code I have:
private void updateNewsButton()
{
// load the original bitmap and draw the number of news on it to show it
Paint paint = new Paint();
paint.setColor( Statics.COLOR_GENERAL_HIGHLIGHT );
paint.setTextAlign( Paint.Align.CENTER );
paint.setTextSize( 24 );
paint.setTypeface( Typeface.defaultFromStyle( Typeface.BOLD ) );
paint.setAntiAlias( true );
Bitmap bmp = BitmapFactory.decodeResource( getResources(), R.drawable.news ).copy( Config.ARGB_8888, true );
Canvas canvas = new Canvas( bmp );
int count = 5; // TODO: load from database
canvas.drawText( Integer.toString( count ), bmp.getWidth() / 2, bmp.getHeight() / 2, paint );
Drawable d = new BitmapDrawable( bmp );
_btnNews.setCompoundDrawables( d, null, null, null );
}
The image on my button just disappears after running the above code. I can't see what I'm doing wrong, because I've used the similare technique for an ImageView before. In there everything is the same except the last two lines. For the ImageView I just assign the bitmap directly:
...
imageView.setImageBitmap( bmp );
I need to use the drawableLeft here, because there are a few other bottons, so I can't use an ImageView again.
Any idea what's wrong with my code?
Upvotes: 2
Views: 2233
Reputation: 3353
To put the image on left in a button programmatically, use the code below
Button button = (Button) findViewById(R.id.mybutton);
button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.img, 0, 0, 0);
where the position is like this (left, top, right, bottom)
Upvotes: 1