Home » Android » layout – How to set android:layout_alignParentLeft attribute to imageview in code?

layout – How to set android:layout_alignParentLeft attribute to imageview in code?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I want to achieve the same thing in code as it is in this xml (this imageview is inside relative layout):

                          <ImageView   
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:src="@drawable/logo"/>

I know how to set layout width and height, but don’t know how to set layout_alignParentLeft=”true”.

Is it possbile to do this in code?

How to&Answers:
RelativeLayout.LayoutParams params = 
    new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
imageView.setLayoutParams(params);

Answer:

When adding an element to a layout in code, you can provide LayoutParams. In this case, you want to use RelativeLayout.LayoutParms.

You can add a rule to the params to tell it that youwant to ALIGN_PARENT_LEFT.