为什么此ImageView与其父级无法正确对齐?

时间:2012-12-20 09:40:15

标签: android relativelayout

我正在使用以下布局构建应用程序:

RelativeLayout容器有一个ImageView子项作为其背景,另外两个RelativeLayouts作为页面的实际内容。

这些观点的规则如下:

// Define rules and params for views in the container
ImageView backgroundImg = new ImageView(this);
RelativeLayout.LayoutParams lpImg = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
lpImg.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
backgroundImg.setImageResource(R.drawable.baggrund_smartphones_retina);
backgroundImg.setLayoutParams(lpImg);

RelativeLayout mainLayout = (RelativeLayout)findViewById(R.id.fragment_main_layout);
RelativeLayout storeLayout = (RelativeLayout)findViewById(R.id.fragment_store_layout);
RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(screenWidth, LayoutParams.MATCH_PARENT);
RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(screenWidth, LayoutParams.MATCH_PARENT);
lp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
lp2.addRule(RelativeLayout.RIGHT_OF, R.id.fragment_main_layout);
mainLayout.setLayoutParams(lp1);
storeLayout.setLayoutParams(lp2);

root.removeAllViews();

//Add background first to ensure its in the back
snapView.addInfoPage(backgroundImg);
snapView.addInfoPage(mainLayout);

现在这是我的问题。但是我的RelativeLayouts正确地与它们的父对齐,但ImageView不是。相反,imageview是这样的地方:

enter image description here

我做错了什么?

2 个答案:

答案 0 :(得分:1)

可能是您的图片尺寸小于parentLayout的屏幕尺寸。

因此,如果您希望图片适合所有屏幕,请通过xml使用imageView标记中的attribut android:scaleType

<ImageView android:id="@+id/img"
blabla 
blabla 
android:scaleType="fitXY" />

或以编程方式:

imgView.setScaleType(ScaleType.FIT_XY);

答案 1 :(得分:0)

像这样改变

RelativeLayout.LayoutParams lpImg = new RelativeLayout.LayoutParams(screenWidth, LayoutParams.MATCH_PARENT);

取代

RelativeLayout.LayoutParams lpImg = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

并像这样修复imageview

backgroundImg.setLayoutParams(ScaleType.FIT_XY);