android获取视图的所有子视图 [英] android get all subviews of a view
问题描述
我想获取 RelativeLayout
的所有子项.我使用代码得到了这个:
I want to get all children of a RelativeLayout
. I get this using the code:
aditionView.getAllChildren().
但是现在子视图按照添加到该视图的顺序出现.但我希望它们按放置在视图中的位置递增顺序排列.
But now the subviews are coming in the order in which it is added into that view. But i want them in the increasing order of position in which it is placed in the view.
推荐答案
您可以通过 View.getLeft() 对子项进行排序
You could sort children by View.getLeft()
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
logCoordinates();
}
private void logCoordinates() {
RelativeLayout layout = (RelativeLayout)findViewById(R.id.layout);
for (int i = 0; i < layout.getChildCount(); i++) {
View child = layout.getChildAt(i);
Log.i("tag", String.format("%d %d %d %d", child.getLeft(), child.getTop(), child.getRight(), child.getBottom()));
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
logCoordinates();
}
请比较从 onCreate()
和 onWindowFocusChanged()
调用的 logCoordinates()
的日志输出.视图坐标在 onCreate()
中不可用(为什么?).请参阅此处的讨论如何获取按钮的高度和宽度
Please, compare log output of logCoordinates()
called from onCreate()
and from onWindowFocusChanged()
. View coordinates are not available within onCreate()
(why?).
See discussion here How to get height and width of Button
这篇关于android获取视图的所有子视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!