如何以编程方式删除在 XML 中定义的现有规则? [英] How do I programmatically remove an existing rule that was defined in XML?
问题描述
我有一个包含在相对布局中的线性布局.它在 XML 文件中设置为另一个线性布局的右侧(这很好用).在某些情况下,我想在活动的 onCreate 期间更改布局的相对位置,因此我需要修改右侧"参数以与另一个布局相关.我试过这个:
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(
有什么线索吗?
推荐答案
您无法删除规则,因为所有规则始终存储在固定大小的 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);
编辑(感谢 Roger Rapid):
从 API 级别 17 开始,RelativeLayout.LayoutParams
类具有以下方法:
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);
这篇关于如何以编程方式删除在 XML 中定义的现有规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!