如何编程删除XML中定义的现有规则?定义、规则、XML

2023-09-12 07:21:29 作者:不羁

我有一个是包含一个相对布局内的线性布局。 它是在XML文件中设定得到的另一个线性布局右侧(本工作正常)。 在某些情况下,我想活动的onCreate期间改变布局的相对位置,所以我需要修改,以右侧的参数涉及到另一个布局。 我trye​​d这样的:

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

不过,这是行不通的:O(

But it does not work :o(

任何线索?

推荐答案

您不能删除一个规则,因为所有的规则总是存储在一个固定大小的Java数组。但是你可以设置一个规则来 0 。例如

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

修改(感谢罗杰快速):

由于API级别17,类 RelativeLayout.LayoutParams 的有以下方法:

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

public void removeRule(int verb) 

所以,你可以用code以下行删除规则:

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.

 
精彩推荐
图片推荐