Setting of ImageView's gravity to the center in android programmatically

73,356

Solution 1

Try this

LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(width, height);
layoutParams.gravity=Gravity.CENTER;
ImageIcons[i].setLayoutParams(layoutParams);

Solution 2

get the layout parameters from view, modify it and set it again.

image.setBackgroundResource(R.drawable.mobile);
LayoutParams params = (LayoutParams) image.getLayoutParams();
params.gravity = Gravity.CENTER;
image.setLayoutParams(params);

Solution 3

First made the width to match_parent and then set the gravity else gravity will not work.Hope it will work.

ImageIcons[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
ImageIcons.setGravity(Gravity.CENTER);

Solution 4

ImageView myImage = new ImageView(this);
FrameLayout.LayoutParams myImageLayout = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.WRAP_CONTENT);
myImageLayout.gravity=Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
            myImage.setLayoutParams(myImageLayout);
Share:
73,356

Related videos on Youtube

Vivek Kalkur
Author by

Vivek Kalkur

App Developer

Updated on July 09, 2022

Comments

  • Vivek Kalkur
    Vivek Kalkur almost 2 years

    I want to set the gravity of an array of Imageviews,ImageIcons[i] to the center with the following code,

    ImageIcons[i] = new ImageView(this);
    ImageIcons[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
    LayoutParams.WRAP_CONTENT));
    layout.addView(ImageIcons[i]);
    

    And I am stuck up while setting the gravity.I request the SO people to guide me on this.

    Thanks

    • Sindri Þór
      Sindri Þór over 8 years
      Check out my answer here. It helped my centralize Imageview.
  • Vivek Kalkur
    Vivek Kalkur over 12 years
    Perfect @Walid Hossain.Thanks a lot.
  • Vivek Kalkur
    Vivek Kalkur over 12 years
    Ok got that.Was wondering what went wrong.Thanks to Android Killer.