1

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

Kostya Khuta
  • 1,846
  • 6
  • 26
  • 48

3 Answers3

3

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);
Houcine
  • 24,001
  • 13
  • 56
  • 83
0

You cannot directly set params to your ImageView you should use ImageIcons instead

Try this:

ImageIcons[i] = new ImageView(this);
ImageIcons[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
layoutParams.gravity=Gravity.CENTER;
ImageIcons[i].setLayoutParams(layoutParams);

Hope it works.. works fine for me.!

Ankit Dhadse
  • 1,566
  • 1
  • 15
  • 19
-1

You could use a RelativeLayout and its centerInParent property like zozelfelfo said or you could stick with LinearLayout and try this :

LinearLayout.LayoutParams b = new LinearLayout.LayoutParams(
                        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

                ivOne.setScaleType(ImageView.ScaleType.CENTER);

                ivOne.setLayoutParams(b);

But in this method, your ImageView will take up the entire layout so be careful if you have other views in it too. If you do, then you're best bet is to use RelativeLayout

Community
  • 1
  • 1
Akash
  • 631
  • 1
  • 8
  • 16
  • 06-27 12:35:17.076: E/AndroidRuntime(3357): Caused by: java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams – Kostya Khuta Jun 27 '13 at 09:34