如何通过java代码在android中将布局居中垂直?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3053864/
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 08:29:32  来源:igfitidea点击:

how to center layout to vertical in android through java code?

android

提问by UMAR

friends,

朋友们,

i want to set android:layout_centerVertical="true" property of layout through java code of an image.

我想通过图像的 java 代码设置布局的 android:layout_centerVertical="true" 属性。

can any one guide me how to achieve this. here is my code.

任何人都可以指导我如何实现这一目标。这是我的代码。

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);

params.height = (int)totalHeight;

img.setLayoutParams(params);

i have tried using setScaleType(ScaleType.FIT_CENTER) but no use.

我曾尝试使用 setScaleType(ScaleType.FIT_CENTER) 但没有用。

any help would be appriciated.

任何帮助将被appriciated。

回答by Balaji

Try this Code..

试试这个代码..

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams
          ((int) LayoutParams.WRAP_CONTENT, (int) LayoutParams.WRAP_CONTENT);

params.addRule(RelativeLayout.CENTER_VERTICAL);

img.setLayoutParams(params);

回答by Keith

Correct me if I'm wrong but it sounds like you are trying to set the alignment (or positional orientation) of an image inside of a layout? To do that you need to set the gravity property of the layout containing the View you align.

如果我错了,请纠正我,但听起来您正在尝试设置布局内图像的对齐方式(或位置方向)?为此,您需要设置包含您对齐的视图的布局的重力属性。

    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);

    RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.FILL_PARENT, 
            RelativeLayout.LayoutParams.WRAP_CONTENT);

    ImageView imageView = new ImageView(this);
    imageView.setLayoutParams(params);
    imageView.setImageBitmap(bitmap);

    layout.setGravity(Gravity.CENTER_VERTICAL | Gravity.TOP);
    layout.addView(imageView);

In this example I'm programmatically adding an image to a RelativeLayout in my layout resource, adding an ImageView, and aligning it so it will be placed at the top, vertical center position.

在此示例中,我以编程方式将图像添加到布局资源中的 RelativeLayout、添加 ImageView 并对齐它,以便将其放置在顶部的垂直中心位置。

回答by arufian

In the new SDK there's no Gravity.VERTICAL_CENTER, but maybe you could set this with layout.setGravity(Gravity.CENTER).

在新的 SDK 中没有Gravity.VERTICAL_CENTER,但也许您可以使用 layout.setGravity(Gravity.CENTER).