本文介绍了如何使用代码而不是 xml 设置 ImageView 的边距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将未知数量的 ImageView 视图添加到我的布局中并带有边距.在 XML 中,我可以像这样使用 layout_margin:

I want to add an unknown number of ImageView views to my layout with margin. In XML, I can use layout_margin like this:

<ImageView android:layout_margin="5dip" android:src="@drawable/image"/>

ImageView.setPadding(),但没有ImageView.setMargin().我认为它与 ImageView.setLayoutParams(LayoutParams) 类似,但不知道该输入什么.

There is ImageView.setPadding(), but no ImageView.setMargin(). I think it's along the lines of ImageView.setLayoutParams(LayoutParams), but not sure what to feed into that.

有人知道吗?

推荐答案

android.view.ViewGroup.MarginLayoutParams 有一个方法 setMargins(left, top, right, bottom).直接子类是:FrameLayout.LayoutParamsLinearLayout.LayoutParamsRelativeLayout.LayoutParams.

android.view.ViewGroup.MarginLayoutParams has a method setMargins(left, top, right, bottom). Direct subclasses are: FrameLayout.LayoutParams, LinearLayout.LayoutParams and RelativeLayout.LayoutParams.

使用例如线性布局:

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(left, top, right, bottom);
imageView.setLayoutParams(lp);

MarginLayoutParams

这会以像素为单位设置边距.要扩展它,请使用

This sets the margins in pixels. To scale it use

context.getResources().getDisplayMetrics().density

DisplayMetrics

这篇关于如何使用代码而不是 xml 设置 ImageView 的边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 02:48