如何访问线性布局中的膨胀视图

How to access inflated views in a linear layout

我使用布局充气器来充气线性布局,其中包含一些按钮和一些文本视图。我如何访问展开布局中的小部件?

例如:我有一个按钮,我想为它设置onclick监听器。通常,您使用 'findViewById' 声明按钮,然后设置侦听器。但是膨胀按钮不存在于 activity xml 中(线性布局在不同的 xml 而不是 activity xml 中)以找到它们使用 'findViewById'.

查看

我的充气机代码:

 LinearLayout item = (LinearLayout )findViewById(R.id.linear_layout_duel_basic_easy);
            View child_1 = getLayoutInflater().inflate(R.layout.linear_layout_duel_1, null);
            item.addView(child_1);

我想要填充的布局:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:orientation="horizontal"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="TextView" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button" />
</LinearLayout>

感谢您的帮助。

您是否尝试过覆盖 onFinishInflate()

您可以在里面查找充气按钮,您可以简单地遍历所有 children 以找到您需要的视图。

//iterate children
for (int index = 0; index < getChildCount(); index+=1){
            getChildAt(index);
//check if that view is what you need
        }

根据评论:

In the activity xml i have a vertical linear layout (created for scroll view) and in the xml that i use to inflate a have a horizontal linear layout where a button and a textview are

这是实现它的方法。

LinearLayout item = (LinearLayout)findViewById(R.id.linear_layout_duel_basic_easy); // Your vertical linearLayout
View child_1 = getLayoutInflater().inflate(R.layout.linear_layout_duel_1, null);// Your Horizontal LinearLayout
item.addView(child_1);

要访问水平 LinearLayout 内的视图:-

TextView tv = child_1.findViewById(R.id.textView);
Button btn = child_1.findViewById(R.id.button);

应该可以。这里没什么特别的。

   LinearLayout item = findViewById(R.id.linear_layout_duel_basic_easy);
    for (int i = 0 ; i < 10; i++) {
        View child = getLayoutInflater().inflate(R.layout.linear_layout_duel_1, null);
        item.addView(child);
        final int finalI = i;
        child.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "clicked = " + finalI, Toast.LENGTH_LONG).show();
            }
        });
    }