如何使用code设置ImageView的保证金,而不是XML [英] How to set margin of ImageView using code, not xml
问题描述
我想数目不详的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的机器人:layout_margin =5dip机器人:SRC =@可绘制/图像/>
有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(左,上,右,下)。直子类是: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:
Using e.g. LinearLayout:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(left, top, right, bottom);
imageView.setLayoutParams(lp);
<一个href="http://developer.android.com/reference/android/view/ViewGroup.MarginLayoutParams.html">MarginLayoutParams
这台以像素为单位的利润。为了扩展它使用
This sets the margins in pixels. To scale it use
context.getResources().getDisplayMetrics().density
<一个href="http://developer.android.com/reference/android/util/DisplayMetrics.html#density">DisplayMetrics
这篇关于如何使用code设置ImageView的保证金,而不是XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!