How do I programmatically remove an existing rule that was defined in XML?
Asked Answered
M

3

71

I have a linear layout that is contained inside a relative layout. It is set in the XML file to be to the right of another linear layout (this works fine). In some cases I want to change the relative position of the layout during the onCreate of the activity so I need to modify the "to the right of" param to relate to another layout. I tryed this:

    RelativeLayout.LayoutParams layoutParams;

    layoutParams = (RelativeLayout.LayoutParams) linearLayoutToMove
            .getLayoutParams();
    layoutParams.addRule(RelativeLayout.RIGHT_OF,
            R.id.new_ref_LinearLayout);

But it does not work :o(

Any clues ?

Misdoing answered 24/2, 2011 at 16:47 Comment(0)
R
155

You can't remove a rule because all rules are always stored in a fixed-size java array. But you can set a rule to 0. For example

layoutParams.addRule(RelativeLayout.RIGHT_OF, 0);
layoutParams.addRule(RelativeLayout.BELOW, R.id.new_ref_LinearLayout);

EDIT (thanks to Roger Rapid):

As of API level 17, the class RelativeLayout.LayoutParams has the following method:

public void removeRule(int verb) 

So you can remove a rule using the following line of code:

layoutParams.removeRule(RelativeLayout.RIGHT_OF);

And you will get exactly the same result as when 'adding' a zero-rule as:

layoutParams.addRule(RelativeLayout.RIGHT_OF, 0);
Richart answered 24/2, 2011 at 21:36 Comment(3)
As of API level 17, the class RelativeLayout.LayoutParams has the following method: public void removeRule (int verb)Lytic
What do I do for apps before api level 17? :oCreodont
@Creodont Setting a rule to 0 is similar to removing the rule.Richart
F
3

I think you need to call:

relativeLayout.updateViewLayout(linearLayoutToMove, layoutParams);

after changing the LayoutParams.

In reply to the edit, you can create new LayoutParameters using:

LinearLayout.LayoutParams = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.FILL_PARENT,
    LinearLayout.LayoutParams.FILL_PARENT);

and then add your new rules. Then, update the layout parameters using the previously mentioned updateViewLayout() method.

Fults answered 24/2, 2011 at 16:55 Comment(0)
I
0

add the following code to your existing code

linearLayoutToMove.setLayoutParams(layoutParams)

I think this should do the job. In case if the above line dont work, try to call linearLayoutToMove.invalidate() after the above line.

Instrumentality answered 24/2, 2011 at 16:54 Comment(1)
Since I am in onCreate, I do not need to call invalidate().Misdoing

© 2022 - 2024 — McMap. All rights reserved.