简体   繁体   中英

Android Button Is Not Changing Image To Fit Inside

I am programatically creating a button. However no matter what I set the button icon is appearing outside the bounds of the box. I want the image to to fit inside the button dimensions. Change my scale type has no effect (CENTER_CROP looks the same as FIT_CENTER) so likely theres something fundamentally wrong with my code. If you can suggest what I am doing wrong I'd appreciate it:

    int buttonDimension = 100;

    _cancelSelectPhotoButton = new ImageButton(this);
    _cancelSelectPhotoButton.setImageResource(R.drawable.deselecticon);
    _cancelSelectPhotoButton.setPadding(0, 0, 0, 0);
    _cancelSelectPhotoButton.setScaleType(ImageView.ScaleType.CENTER_CROP);//all scale types look the same
    _cancelSelectPhotoButton.setAdjustViewBounds(false);//true has no effect either
    _cancelSelectPhotoButton.setMinimumHeight(buttonDimension);
    _cancelSelectPhotoButton.setMaxHeight(buttonDimension);
    _cancelSelectPhotoButton.setMinimumWidth(buttonDimension);
    _cancelSelectPhotoButton.setMaxWidth(buttonDimension);
    _cancelSelectPhotoButton.setX(0);

在此处输入图片说明

I just tested it and the following combination worked for me:

 _cancelSelectPhotoButton.setScaleType(ImageView.ScaleType.FIT_CENTER);
 _cancelSelectPhotoButton.setAdjustViewBounds(true);

This is what i'm getting. I added a background color to the ImageButton and a padding in order to see the actual box.

在此处输入图片说明

NOTE:

After testing with different approaches, we found out that if you set a background color to the ImageButton, the image fits correctly. Without it, somehow works on Nexus 5 but not on Nexus 6.

_cancelSelectPhotoButton.setBackgroundColor(Color.TRANSPARENT);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM