如何使用代码而不是 xml 设置 ImageView 的边距

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to target newer versions in .gitlab-ci.yml using auto devops (java 11 instead of 8 and Android 31 instead of 29)(如何在.gitlab-ci.yml中使用自动开发工具(Java 11而不是8,Android 31而不是29)瞄准较新的版本)
Android + coreLibraryDesugaring: which Java 11 APIs can I expect to work?(Android+core LibraryDesugering:我可以期待哪些Java 11API能够工作?)
How to render something in an if statement React Native(如何在If语句中呈现某些内容Reaction Native)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)
Using Firebase Firestore in offline only mode(在仅脱机模式下使用Firebase FiRestore)
Crash on Google Play Pre-Launch Report: java.lang.NoSuchMethodError(Google Play发布前崩溃报告:java.lang.NoSuchMethodError)