【问题标题】:How to programmatically change layout_width and layout_height of image? [duplicate]如何以编程方式更改图像的 layout_width 和 layout_height? [复制]
【发布时间】:2021-10-02 01:57:02
【问题描述】:
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 是一个ImageButton,点击它是一个ImageButton,应该是换成另一个图像。但是,我不知道如何更改图像的layout_widthlayout_height。我设法弄清楚如何更改图像的比例类型。 btnRepeat.setMinimumHeight(70);btnRepeat.setMinimumWidth(70); 在我的情况下不起作用。

那我该如何改变呢?提前谢谢你。

【问题讨论】:

标签: android imageview runtime


【解决方案1】:

当您以编程方式在 LayoutParams 中指定值时,这些值应为像素。

要在像素和 dp 之间进行转换,您必须乘以当前密度因子。 所以我们可以在 DisplayMetrics 中使用,您可以从 Context 访问,如下所示:

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

您需要将整数值乘以因子值。

不用设置 setMinmumHeoght 和 setMinimumWidth ,你可以试试下面的代码:

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

【讨论】:

  • 成功了。但是,布局像素数与 getLayoutParamas() 的像素数不成比例。既然是这种情况,当它首先作为 ImageButton 放置时,如何使正确的 int 放置为相同大小的图标?提前谢谢你。
  • 感谢您的回复。我已经更新了我的答案
猜你喜欢
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-18
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 2021-01-14
相关资源
最近更新 更多