如何通过java代码在android中将布局中心化?

UMA*_*MAR 14 android

朋友们,

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

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

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

params.height = (int)totalHeight;

img.setLayoutParams(params);
Run Code Online (Sandbox Code Playgroud)

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

任何帮助都会得到满足.

Bal*_*aji 44

试试这个代码..

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

params.addRule(RelativeLayout.CENTER_VERTICAL);

img.setLayoutParams(params);
Run Code Online (Sandbox Code Playgroud)


Kei*_*ith 24

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

    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);
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我是以编程方式将图像添加到我的布局资源中的RelativeLayout,添加一个ImageView,并对齐它,使其位于顶部的垂直中心位置.