你如何改变ImageView的大小?

ate*_*dja 17 android imageview layoutparams

我已经设置了我的ImageView,如下所示:

    <ImageView android:id="@+id/dl_image"
               android:layout_width="60dp"
               android:background="@drawable/pictureframe"
               android:layout_height="wrap_content"
               android:layout_marginRight="10dp"
               android:layout_alignParentLeft="true"
               android:layout_centerVertical="true"
               android:adjustViewBounds="true"
               android:scaleType="fitCenter"/>
Run Code Online (Sandbox Code Playgroud)

请注意,layout_width固定为60dp.根据我在线获取的内容,我想将此宽度调整为90dp或120dp(同时保持图像的宽高比).

我尝试使用setLayoutParams,但传递LayoutParams(120,LayoutParams.WRAP_CONTENT)会引发异常.它似乎不喜欢它.

如果可能的话,我试图避免为更大的尺寸制作另一个ImageView.

Pet*_*tai 38

如果您正在使用现有视图,那么LayoutParams从头开始创建一组新工具可能需要做很多工作.相反 - 您可以抓取视图的现有LayoutParams,编辑它们,然后将它们应用到视图以使用它来更新其LayoutParamssetLayoutParams()

ImageView imageView = findViewById(R.id.dl_image);
LayoutParams params = (LayoutParams) imageView.getLayoutParams();
params.width = 120;
// existing height is ok as is, no need to edit it
imageView.setLayoutParams(params);
Run Code Online (Sandbox Code Playgroud)

确保导入正确的类型LayoutParams.对于这种情况,正如您所评论的那样,您只需使用LayoutParamsa即可ViewGroup.如果您要设置特定于某种类型视图的参数(例如,RelativeLayouts中的对齐),则必须导入该LayoutParams类型的视图.

  • @alnite - 很高兴能帮到你.感谢您让我了解`ViewGroup`,编辑了答案以反映. (2认同)

tib*_*bbi 6

你可以做到这一切

ImageView imageView = findViewById(R.id.dl_image);
imageView.getLayoutParams().width = 120;
Run Code Online (Sandbox Code Playgroud)