Android:如何按类型查找视图

Nei*_*eil 17 android android-layout

好的,我有一个类似于以下示例的布局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>
Run Code Online (Sandbox Code Playgroud)

我实际上有大约7个LinearLayout项目,每个项目的id从layout_0等增加.我希望能够获得根LinearLayout下的所有LinearLayout项目.我是否需要在根目录上放置一个id并通过id找到所有其他ID,或者我可以按类型获取它们.

我用来夸大布局的代码是:

View view = (View) inflater.inflate(R.layout.flight_details, container, false);
Run Code Online (Sandbox Code Playgroud)

我在某处读过你可以迭代ViewGroup的孩子,但这只是一个View.

通过类型获得一堆孩子的最佳方法是什么?

Raw*_*ode 33

这应该让你走上正轨.

LinearLayout rootLinearLayout = (LinearLayout) findViewById(R.id.rootLinearLayout);
int count = rootLinearLayout.getChildCount();
for (int i = 0; i < count; i++) {
    View v = rootLinearLayout.getChildAt(i);
    if (v instanceof LinearLayout) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)