0

In an activity I am changing one of the ViewGroup content runtime: buttons action, other events.

At a specific case I need to check if a child is in this layout or not ( in this case the child is another RelativeLayout, which hold other views)

How can I check runtime, programmatically if child_1_RelativeLayout is there or is already removed from view tree, his parent is parentRelativeLayout

The getParent() is usefully? - not much explanation how to use it, thanks.

4

2 回答 2

2

如果您存储了视图,您可以使用getParent()检查视图是否是其他视图的直接子视图。删除视图后,其父字段将被清除。例如:

ViewGroup parent = ...;
View child = ...;

assert(child.getParent() == parent); // <-- true

parent.removeView(child);

assert(child.getParent() == parent); // <-- false
于 2013-04-25T11:30:46.907 回答
1

不太确定我是否正确理解了您的问题,但是:

  • 添加相对布局时,请务必先给它一个 id(在您的 layout.xml 文件中或从代码中)
  • 要检查 中是否存在相关布局ViewGroup,请使用 ViewGroup 的findViewById()方法(继承自View)并将您提供给相关布局的 id 传递给它
  • 如果返回null,则相对布局不存在,否则findViewById()会找到

所以简而言之,findViewById()它不仅是为一个 Activity 定义的,而且你可以在任何你想用作搜索起点的视图上调用它。

于 2013-04-25T11:17:01.640 回答