如何在Android SDK中更改ImageView的宽度

时间:2013-09-05 20:14:11

标签: android imageview

所以我正在尝试学习使用Android应用程序,我有一个名为(id)“img_BarHealth”的ImageView,我初始化为“160dp”。

我已经制作了一个按钮并将其连接到此功能:

public void onBack(View view) {
    //Get link to the object.
    ImageView bar_Health = (ImageView) findViewById(R.id.img_BarHealth);

    //This is what I want done. (However this value is not accessable it seems)
    bar_Health.width = "80dp";
}

那么,有什么建议吗? =)

2 个答案:

答案 0 :(得分:0)

使用 getLayoutParams()。width

ImageView bar_Health = (ImageView) findViewById(R.id.img_BarHealth);
    bar_Health.getLayoutParams().width = 80;

答案 1 :(得分:0)

您必须致电getLayoutParams().width,然后才需要转换dip to pixel size

public int convertDipToPixels(float dips)
{
    return (int) (dips * getResources().getDisplayMetrics().density + 0.5f);
}

工作的东西将接近:

bar_Health.getLayoutParams().width = convertDipToPixels(80);