Why is setMargins not working with my RelativeLayout?

时间:2015-06-30 13:38:45

标签: android android-layout

I have a RelativeLayout inside of another Relative Layout.When i use the inner layout to be LinearLayout the code works fine however.I read about many such questions here on SO.Sometimes it was mentioned that the layout params used should be of the parent layout. I wasnt able to quite understand it.Is this where I am going wrong?

Thanks in advance guys !

MY XML FILE

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tools="http://schemas.android.com/tools"   
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:id="@+id/rel1"  >

<RelativeLayout
    android:id="@+id/ll"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true" >

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="120dp"
    android:layout_height="60dp"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_marginRight="20dp"
    android:src="@drawable/helo" />

     </RelativeLayout>

</RelativeLayout>   

Function Where I use margins

public void showcopter()
     {
          ImageView image=(ImageView)findViewById(R.id.imageView1);           
          RelativeLayout.LayoutParams lp=(RelativeLayout.LayoutParams)(image.getLayoutParams());
          lp.leftMargin =0;//(int)((width-150)*density);
          lp.topMargin=(int)(hg-(30*density));   //hg is a global variale which stores the screen height
     //   Log.d("hello_girl",hg+" ");
     //   lp.setMargins((int) ((width-150)*density),(int)(hg-(30*density)),0,0);   
          image.setLayoutParams(lp);
          image.requestLayout();
     }

1 个答案:

答案 0 :(得分:2)

由于你已经将android:layout_alignParentRight设置为true,因此leftMargin不会生效,而当你将android:layout_centerVertical设置为true时,topMargin也不会生效。