How to set margin of ImageView using code, not xml(如何使用代码而不是 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.LayoutParams
、LinearLayout.LayoutParams
和 RelativeLayout.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 的边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用代码而不是 xml 设置 ImageView 的边距


基础教程推荐
- iOS4 创建后台定时器 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01