0
public void repeatSong(View view)
{
    if (repeatFlag) //If repeatFlag (Repeat Function) is activated
    {
        //onClick, icon change to dactivated state
        btnRepeat.setBackgroundResource(R.drawable.repeatwhiteicon);
        btnRepeat.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        btnRepeat.setMinimumHeight(70);
        btnRepeat.setMinimumWidth(70);
    }

    else //If repeatFlag (Repeat Function) is deactivated
    {
        //onClick, icon change to activated state
        btnRepeat.setBackgroundResource(R.drawable.repeatblueicon);
        btnRepeat.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    }

        // onClick, repeatSong function is inverted (Activated-Deactivated OR Deactivated-Activated)
        repeatFlag = !repeatFlag;

}

btnRepeat is a ImageButton, it is a ImageButton when clicked, is supposed to changed to another image. However, I do not know how to change the layout_width and layout_height of the image. I managed to figure out how to change the scale type of the image. btnRepeat.setMinimumHeight(70); and btnRepeat.setMinimumWidth(70); did not work in my case.

How do I change it then? Thank you in advance.

Deep Patel
  • 2,584
  • 2
  • 15
  • 28
  • 3
    Does this answer your question? [Set ImageView width and height programmatically?](https://stackoverflow.com/questions/3144940/set-imageview-width-and-height-programmatically) – Hellious Jul 26 '21 at 05:02

1 Answers1

1

When you specify values programmatically in the LayoutParams, those values are expected to be pixels.

To convert between pixels and dp you have to multiply by the current density factor. So we can use in the DisplayMetrics, that you can access from a Context as below :

float factor = btnRepeat.getResources().getDisplayMetrics().density;

You need to multiply your integer values with the factor value.

Instead of set setMinmumHeoght and setMinimumWidth ,You can try below code :

btnRepeat.getLayoutParams().height = (int)(70*factor) ;
btnRepeat.getLayoutParams().width = (int)(70*factor) ;

//this line redraws the imageview again call only after you set the size
btnRepeat.requestLayout();
  • It worked. However, the layout pixel count is not propotional to that of getLayoutParamas(). Since that is the case, how do I make the correct int to place for icon to be of the same size when it was placed as a ImageButton in the first place? Thank you in advance. – Jason Chua Jul 27 '21 at 01:27