How to set ImageView in the center of layout from code?

Kostya Khuta picture Kostya Khuta · Jun 27, 2013 · Viewed 11.1k times · Source

I try next

LinearLayout.LayoutParams b = new LinearLayout.LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                b.gravity =Gravity.CENTER;

                ivOne.setLayoutParams(b);

But this does no work, image view in the left side of layout

Answer

Houcine picture Houcine · Jun 27, 2013

try to change the parent layout to RelativeLayout , and use the attribute centerInParent :

RelativeLayout rootLayout = new RelativeLayout(this);
rootLayout.setLayoutParams( new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
ImageView ivOne = new ImageView(this);
ivOne.setImageResource(R.drawable.ic_launcher);
ivOne.setScaleType(ImageView.ScaleType.CENTER);
ivOne.setLayoutParams(params);
//TODO : add other views 
rootLayout.addView(ivOne);