Android 如何使用代码设置 ImageView 的重力(或边距)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2618331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:36:26  来源:igfitidea点击:

How to set gravity (or margins) of ImageView using code?

android

提问by Mastojun

I want to add ImageView to FrameLayout with Gravity or margins. but FramLayout and ImageView has no method about that(Actually, I can't found that). Reason that selects Framelayout is to put ImageView on ImageView.

我想将 ImageView 添加到带有 Gravity 或边距的 FrameLayout。但是 FramLayout 和 ImageView 对此没有任何方法(实际上,我找不到)。选择Framelayout的原因是把ImageView放在ImageView上。

Help me plz. It is emergency for me to find solution.

请帮帮我。我急需找到解决办法。

thx.

谢谢。

Below is my code which help understanding my question.

以下是我的代码,有助于理解我的问题。

FrameLayout imageFrame = new FrameLayout(mContext);
imageFrame.setLayoutParams(new GridView.LayoutParams(158, 158));

ImageView frame = new ImageView(mContext);
frame = new ImageView(mContext);
frame.setLayoutParams(new LayoutParams(158, 158));
frame.setScaleType(ImageView.ScaleType.CENTER_CROP);
frame.setImageResource(R.drawable.image_frame_n);

ImageView image = new ImageView(mContext);
image.setLayoutParams(new LayoutParams(148, 148));
image.setScaleType(ImageView.ScaleType.CENTER_CROP);
image.setImageResource(mThumbIds[position]);
// image is needed to have a margin or gravity to be positioned at center of imageFrame

imageFrame.addView(image);
imageFrame.addView(frame);

回答by hpique

Try:

尝试:

image.setLayoutParams(new FrameLayout.LayoutParams(width, height, gravity));

More info:

更多信息:

http://developer.android.com/reference/android/widget/FrameLayout.LayoutParams.html

http://developer.android.com/reference/android/widget/FrameLayout.LayoutParams.html