如何从代码中设置ImageView在布局的中心?

时间:2013-06-27 09:14:44

标签: android android-layout layout-gravity

我尝试下一步

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

                ivOne.setLayoutParams(b);

但这不起作用,布局左侧的图像视图

3 个答案:

答案 0 :(得分:3)

尝试将父级布局更改为RelativeLayout,并使用属性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);

答案 1 :(得分:0)

您无法直接将params设置为ImageView,而应使用ImageIcons代替

试试这个:

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

希望它有效..对我来说很好。!

答案 2 :(得分:-1)

您可以使用RelativeLayout及其centerInParent属性,例如zozelfelfo,或者您可以坚持使用LinearLayout并尝试:

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

                ivOne.setScaleType(ImageView.ScaleType.CENTER);

                ivOne.setLayoutParams(b);

但是在这种方法中,你的ImageView将占用整个布局,所以如果你有其他视图也要小心。如果你这样做,那么你最好的选择是use RelativeLayout