好了,我有一个类似于下面例子的布局xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/tile_bg" >
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingTop="10dp" >
<LinearLayout
android:id="@+id/layout_0"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<!-- view stuff here -->
</LinearLayout>
<!-- more linear layouts as siblings to this one -->
</LinearLayout>
我实际上有大约7个LinearLayout项目,每个项目的id从layout_0开始增加。我希望能够获得根LinearLayout下的所有LinearLayout项。我需要把一个id放在根一个,并找到所有其他的id或我可以得到他们的类型。
我用来填充布局的代码是:
View view = (View) inflater.inflate(R.layout.flight_details, container, false);
我在某个地方读到过,你可以迭代ViewGroup的孩子,但这只是一个视图。
什么是最好的方式得到一群孩子的类型?
9条答案
按热度按时间eivgtgni1#
这应该会让你走上正轨。
wbrvyc0a2#
如果你知道你的布局的根元素是任何子类,比如
LinearLayout
或其他Layouts,你可以安全地将结果视图转换为ViewGroup
:想用就用如果你知道你将总是只使用一种类型的布局作为根容器,你可以强制转换为该类型,即:
dldeef673#
Kotlin版本的Mir-Ismaili回答:
调用它,例如:
myViewGroup.getViewsByType(EditText::class.java)
vlurs2pr4#
您应该向LinearLayout根目录添加一个id:
然后像往常一样膨胀整个布局:
获取根目录
LinearLayout
:9vw9lbht5#
将根视图作为此DFS方法的参数传递:
cyvaqqii6#
我只是想添加一个更通用的方法,但您必须记住,这样做是一种繁重的方法。
代码如下:
ghg1uchk7#
类似@ChristopheCVB的答案,但也支持继承(参见
tClass.isInstance(child)
)。一个简单的使用示例:
感谢接受的回答。
t3psigkw8#
简单的Kotlin代码(如果父节点是
ViewGroup
类型,例如LinearLayout
、FrameLayout
...在您的例子中,LinearLayout
也是ViewGroup
的子类型。)如果它不止一个。
l3zydbqr9#
在我的自定义布局的情况下,所有的答案都不起作用。因为这些答案只检查子视图中的类是否存在,但是根视图本身可以是类。所以使用下面的代码解决了我的问题。
活动中