【发布时间】:2018-04-30 08:12:08
【问题描述】:
我使用布局充气器,用一些按钮和一些文本视图来充气线性布局。如何访问膨胀布局中的小部件?
例如:我有一个按钮,我想为它设置 onclick 监听器。通常,您使用“findViewById”声明按钮,然后设置侦听器。但是活动 xml 中不存在膨胀按钮(线性布局在不同的 xml 中,而不是在活动 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>
感谢您的帮助。
【问题讨论】:
-
试试 child_1.findViewById(R.id.btn_id)
标签: java android android-inflate