Question

I have following relative layout:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/relativeLayoutScrollableForCentering"
    android:layout_below="@+id/addressOfProvider"
    android:layout_centerHorizontal="true">

I want to change the attribute "layout_centerHorizontal" programmatically. How can I do that?

I'm not sure which layout parameters to set:

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
               LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

to achieve just what I want after getting the relative layout by using:

RelativeLayout relLayoutForCentering = 
    (RelativeLayout)view.findViewById(R.id.relativeLayoutScrollableForCentering);

?

Was it helpful?

Solution

You can add and remove rules for RelativeLayout.LayoutParams with the addRule and removeRule methods:

layoutParams.removeRule(RelativeLayout.CENTER_HORIZONTAL);
layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);

OTHER TIPS

android:layout_centerHorizontal is not the view's child's attribute but the attribute of the view itself

catch the layout and set the gravity of layout.

RelativeLayout lay=(RelativeLayout)findViewById(R.id.lay);
        lay.setGravity(Gravity.CENTER_HORIZONTAL);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top