2

次のようにXMLでdrawableLeftを割り当てるLinearLayoutにボタンがあります。

<Button android:id="@+id/button_news"
    style="@style/main_button"
    android:drawableLeft="@drawable/news"
    android:text="@string/button_news" />

これは正常に機能し、ボタンは期待どおりに見えます。

ここに画像の説明を入力してください

利用可能なニュースの数を表示するために、プログラムで画像を変更したいと思います。これは私が持っているコードです:

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 );
}

上記のコードを実行すると、ボタンの画像が消えます。以前にImageViewに同様の手法を使用したことがあるため、何が間違っているのかわかりません。最後の2行を除いて、すべて同じです。ImageViewの場合、ビットマップを直接割り当てます。

...
imageView.setImageBitmap( bmp );

他にもいくつかのボットンがあるため、ここでdrawableLeftを使用する必要があります。そのため、ImageViewを再度使用することはできません。

私のコードの何が問題になっているのでしょうか?

4

1 に答える 1

1

プログラムでボタンの左側に画像を配置するには、以下のコードを使用します

Button button = (Button) findViewById(R.id.mybutton);   
button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.img, 0, 0, 0);

位置はこんな感じ(左、上、右、下)

于 2013-03-27T04:02:54.807 に答える