Resize image and set it at center of button with textview at bottom

122 views Asked by At

This is how i create my button

Mybutton btn1 = new Mybutton(getApplicationContext());
                                        btn1.setId(20+i);
                                        btn1.setText(jobj1.getString("name"));
                                        btn1.setTextColor(Color.WHITE);
                                        btn1.setWidth(dpToPx(150));
                                        btn1.setHeight(dpToPx(150));
                                        btn1.setGravity(Gravity.BOTTOM|Gravity.CENTER);        // part2
                                        btn1.setPadding(5, 5, 5, 5);
                                        Picasso.with(getApplicationContext()).load(jobj1.getString("image")).into(btn1);
                                        tr_head.addView(btn1);// add the column to the table row here

it create layout like this enter image description here

here is custom mybutton class

public class Mybutton extends Button implements Target {

    public Mybutton(Context context) {
        super(context);
    }

    public Mybutton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public Mybutton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
        setBackgroundDrawable(new BitmapDrawable(bitmap));
    }

    @Override
    public void onBitmapFailed(Drawable errorDrawable) {

    }

    @Override
    public void onPrepareLoad(Drawable placeHolderDrawable) {

    }
}

What i want is to resize the icon so they are small and set them to center of button.also how can i setmargins for left and right of this button

1

There are 1 answers

3
A.S On

there are several options to do this: you can resize the original image in the drawable files and set width and height to wrap_content or you can use

btn.setScaleType(yourType);

here is a method that might help to scale your image:

public static Bitmap scaleDownBitmap(Bitmap photo, int newHeight,int newWidth, Context context) {
        photo=Bitmap.createScaledBitmap(photo, newWidth, newHeight, true);
        return photo;
         }

to set margins for button pragmatically use:

    LayoutParams params = new LayoutParams(
        LayoutParams.WRAP_CONTENT,      
        LayoutParams.WRAP_CONTENT
        );
    params.setMargins(left, top, right, bottom);
    yourbutton.setLayoutParams(params);