Marcel Marino
Marcel Marino

Reputation: 1002

Android - Layout Not Centering

I'm confused, this should be centering, yet it's not.

public void addTableImage(String imageName, LinearLayout L){

    ImageView newImage = new ImageView(c);
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(150, 150);
    newImage.setLayoutParams(layoutParams);

    int id = c.getResources().getIdentifier(imageName, "drawable", c.getPackageName());
    RelativeLayout l1 = new RelativeLayout(c);
    l1.setLayoutParams(new RelativeLayout.LayoutParams(400, 160));
    l1.setBackgroundColor(Color.WHITE);
    l1.setGravity(Gravity.CENTER);

    newImage.setImageResource(id); 
    l1.addView(newImage);
    L.addView(l1);
}

And I'm getting this as a result:

enter image description here

Image shows up fine (yes, it's just a placeholder green box), the background is set, and everything is set to be Gravity.CENTER, yet it's still left oriented.

Bonus points: Anyone know why "Ask a Question" now autocompletes your last question's info? It's a bit confusing, making me think I'm actually editing an old question.

Upvotes: 0

Views: 162

Answers (1)

vipul mittal
vipul mittal

Reputation: 17401

Change your code to:

public void addTableImage(String imageName, LinearLayout L){

    ImageView newImage = new ImageView(c);
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(150, 150);
    newImage.setLayoutParams(layoutParams);

    int id = c.getResources().getIdentifier(imageName, "drawable", c.getPackageName());
    RelativeLayout l1 = new RelativeLayout(c);
    LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(400, 160);
    lp.gravity=Gravity.CENTER;

    l1.setLayoutParams(lp);
    l1.setBackgroundColor(Color.WHITE);
    l1.setGravity(Gravity.CENTER);

    newImage.setImageResource(id); 
    l1.addView(newImage);
    L.addView(l1);
}

Your image is centered inside relativelayout by setting gravity of relative layout to center.

But to set relative layout itself to the center of the Linearlayout it is in you need to set layout gravity to center of relative layout to center or gravity of the LinearLayout to center. You can try above code it should work.

Upvotes: 2

Related Questions