如何以编程方式删除在 XML 中定义的现有规则?
我有一个包含在相对布局内的线性布局。 它在 XML 文件中设置为另一个线性布局的右侧(这很好)。 在某些情况下,我想在活动的 onCreate 期间更改布局的相对位置,因此我需要修改“to the right of”参数以与另一个布局相关。 我尝试了这个:
RelativeLayout.LayoutParams layoutParams;
layoutParams = (RelativeLayout.LayoutParams) linearLayoutToMove
.getLayoutParams();
layoutParams.addRule(RelativeLayout.RIGHT_OF,
R.id.new_ref_LinearLayout);
但它不起作用:o(
有任何线索吗?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法删除规则,因为所有规则始终存储在固定大小的 java 数组中。但您可以将规则设置为
0
。例如编辑(感谢Roger Rapid):
从API级别17开始,类
relativeLayout.LayoutParams
具有以下方法:因此您可以使用以下代码行删除规则:
并且您将获得与“添加”零规则时完全相同的结果:
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 exampleEDIT (thanks to Roger Rapid):
As of API level 17, the class
RelativeLayout.LayoutParams
has the following method:So you can remove a rule using the following line of code:
And you will get exactly the same result as when 'adding' a zero-rule as:
我认为您需要
调用:
relativeLayout.updateViewLayout(linearLayoutToMove, layoutParams);
在更改 LayoutParams 后
。为了回复编辑,您可以使用以下命令创建新的 LayoutParameters:
然后添加新规则。然后,使用前面提到的 updateViewLayout() 方法更新布局参数。
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:
and then add your new rules. Then, update the layout parameters using the previously mentioned updateViewLayout() method.
将以下代码添加到现有代码中
linearLayoutToMove.setLayoutParams(layoutParams)
我认为这应该可以完成这项工作。如果上面的行不起作用,请尝试在上面的行之后调用
linearLayoutToMove.invalidate()
。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.