CodePrimate
CodePrimate

Reputation: 6666

Why is this ImageView not aligning properly with its parent?

I'm building an application with the following layout:

A RelativeLayout container has a ImageView child as its background and two other RelativeLayouts as the actual content of the page.

The rules of these views are set up as follows:

// 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);

Now here is my problem. But my RelativeLayouts are aligning properly to their parent, but the ImageView is not. Instead the imageview is places like this:

enter image description here

What am I doing wrong?

Upvotes: 3

Views: 311

Answers (2)

Houcine
Houcine

Reputation: 24181

may be your image dimensions is smaller than the screen dimensions of your parentLayout .

So if you want the image to Fit all the screen use the attribut android:scaleType in your imageView Tag via xml :

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

or programmatically :

imgView.setScaleType(ScaleType.FIT_XY);

Upvotes: 1

NagarjunaReddy
NagarjunaReddy

Reputation: 8645

change like this

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

In place of

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

And fix imageview like this

backgroundImg.setLayoutParams(ScaleType.FIT_XY);

Upvotes: 0

Related Questions