简体   繁体   English

有孩子的水平LinearLayout从右到左排序?

[英]Horizontal LinearLayout with children ordered right-to-left?

I have a horizontal LinearLayout that's programmatically filled with its children. 我有一个水平的LinearLayout,它以编程方式填充其子代。 I would like to be able to switch to a right-to-left layout (ie child 0 is on the far right, child 1 to its left, etc.) . 我希望能够切换到从右到左的布局(即,子0位于最右侧,子1位于其左侧,等等)。 The thing is, I want the layout to switch from RtL to LtR and back dynamically, that's why eg this question is irrelevant to my case. 问题是,我希望布局从RtL切换到LtR并动态返回,这就是为什么例如这个问题与我的情况无关。

There doesn't seem to be any way to set it directly in the code, especially since gravity is for alignment, not ordering. 似乎没有任何方法可以直接在代码中设置它,特别是因为重力是用于对齐而不是排序。

So far I see the following workarounds: 到目前为止,我看到以下解决方法:

  • On the ordering switch, re-add the children in an inverted order (problem: very ugly and resource-consuming). 在订购开关上,以相反的顺序重新添加子项 (问题:非常难看且耗费资源)。
  • Implement a subclass of LinearLayout with an overridden onLayout() method (problem: lots of copy-pasting the Android source due to helper layout members having a restrictive visibility). 使用重写的onLayout()方法实现LinearLayout的子类 (问题:由于辅助布局成员具有限制性可见性,因此大量复制粘贴Android源)。
  • Replace the LinearLayout with another, eg a TableLayout or a RelativeLayout , and change the layout params of the children on switch (problem: still somewhat kludgey). LinearLayout替换为另一个,例如TableLayoutRelativeLayout ,并更改开关上子项的布局参数 (问题:仍然有点kludgey)。

Any more direct solutions or better workarounds? 有更直接的解决方案或更好的解决方法吗?

EDIT: to clarify, I'm creating the children practically once during the activity run-time, and I can store them in a helper array/collection at no complication to the code. 编辑:澄清一下,我在活动运行期间几乎创建了一次子项,我可以将它们存储在辅助数组/集合中,而不会使代码复杂化。

While re-creating the children might be resource-intensive, re-ordering shouldn't be that bad. 虽然重新创建子项可能是资源密集型的,但重新排序不应该那么糟糕。 You can take the existing views using getChildAt and getChildCount and then put them back in using the addView override with an index . 您可以使用getChildAtgetChildCount获取现有视图,然后使用带索引addView覆盖将它们重新放入。

Do a LinearLayout.setRotationY(180). 执行LinearLayout.setRotationY(180)。 You will also have to set the Y rotation of the child views of the Linear Layout to 180 also. 您还必须将“线性布局”的子视图的Y旋转设置为180。 So for example: 例如:

private void horizontal() {
    LinearLayout layout = (LinearLayout) v.findViewById(R.id.layout);
    View childView1 = (View) v.findViewById(R.id.childView1);
    View childView2 = (View) v.findViewById(R.id.childView2);

    layout.setRotationY(180);
    childView1.setRotationY(180);
    childView2.setRotationY(180);
}

The code may be wrong, but you get the idea. 代码可能是错误的,但你明白了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM