Question

I want to set an Image background at run time on ImageButton. I know I can use the following code:

Bitmap b=bitmap;
ImageButton btn;
btn=(ImageButton)findViewById(R.id.myButton);
btn.setBackground(d);

but the above code requires android API 16, and I am working on lower API. I also know the following code can be used:

ImageButton imgButton = (ImageButton) findViewById(R.id.myButton);
imgButton.setBackgroundResource(R.drawable.myImage);

but with this, I have a problem that the image that I am trying to set is not available in the resources and is generated at run time.

How can I set an image to ImageButton at run time in android with APIs before API level 16.

Thanks

Était-ce utile?

La solution

use setBackgroundDrawable(Drawable)...

    Bitmap b = bitmap;
    ImageButton btn;
    btn = (ImageButton) findViewById(R.id.myButton);
    BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), b);
    btn.setBackgroundDrawable(bitmapDrawable);

Autres conseils

Try this..

btn = (ImageButton) findViewById(R.id.myButton);
BitmapDrawable drawable_bitmap = new BitmapDrawable(getResources(), b);
btn.setBackgroundDrawable(drawable_bitmap);

like @Gopal Rao said

Or

btn = (ImageButton) findViewById(R.id.myButton);
btn.setImageBitmap(b);
public Bitmap getBitmapFromDrawable (@DrawableRes int resId){
    // create bitmap

    Drawable d =ContextCompat.getDrawable(getContext(),res);

    Bitmap bmp = Bitmap.createBitmap(d.getIntrinsicWidth(),
                    d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bmp);
    d.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    d.draw(canvas);

    return bmp;
}

If you want to scale bitmap add this line to the method :

//with x and y as your new width and height
Bitmap newBitmap = Bitmap.createScaledBitmap (bmp,x,y,false);

then:

yourimageview.setImageBitmap(getBitmapFromDrawable(R.drawable.your_drawable));
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top