Search code examples
javaandroidimagebuttonscaletype

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

enter image description here


Solution

  • 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.

    enter image description here

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