Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

friends,

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

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.

any help would be appriciated.

like image 601
UMAR-MOBITSOLUTIONS Avatar asked Jun 16 '10 13:06

UMAR-MOBITSOLUTIONS


People also ask

How do you center a vertical view?

The simple and quick answer is to add android:gravity="center_vertical" to the parent(containing) view.

How do I center something in android Studio?

Adding android:gravity="center" in your TextView will do the trick (be the parent layout is Relative/Linear )!

How can I center text programmatically in android?

To center align text in TextView in Kotlin Android, set android:textAlignment attribute with the value “center” in layout file, or programmatically set the textAlignment property of the TextView object with View. TEXT_ALIGNMENT_CENTER in activity file.


2 Answers

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);
like image 120
Balaji Avatar answered Oct 26 '22 23:10

Balaji


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.

like image 28
Keith Avatar answered Oct 26 '22 23:10

Keith