【发布时间】:2019-04-05 14:51:05
【问题描述】:
我为此搜索了很多,但我无法解决它。我有带有两个文本视图和一个按钮(添加其他 LinearLayout)的 LinearLayout,如下所示:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<EditText android:id="@+id/ingredientsField"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="@dimen/boxes_margin"
android:hint="@string/ingredients"
android:inputType="text"
xmlns:android="http://schemas.android.com/apk/res/android" />
<EditText
android:id="@+id/quantityField"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="@dimen/boxes_margin"
android:hint="@string/quantity"
android:inputType="number"
/>
<com.google.android.material.button.MaterialButton
android:id="@+id/add_ingredient_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/add"
android:layout_margin="@dimen/boxes_margin"
app:icon="@drawable/ic_add_ingr_btn"
/>
</LinearLayout>
添加的布局是这样的:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="50dp">
<EditText android:id="@+id/ingredientsField"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="@dimen/boxes_margin"
android:hint="@string/ingredients"
android:inputType="text"
xmlns:android="http://schemas.android.com/apk/res/android" />
<EditText android:id="@+id/quantityField"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="@dimen/boxes_margin"
android:hint="@string/quantity"
android:inputType="number"
xmlns:android="http://schemas.android.com/apk/res/android" />
<ImageButton
android:id="@+id/remove_ingredient_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="@dimen/boxes_margin"
android:src="@drawable/ic_remove_ing_qnt"/>
</LinearLayout>
在 Activity 中,我创建了一个添加新布局的方法(并且它有效),并在其中创建了一个使用 删除按钮 删除相应布局的方法。删除按钮只工作一次,并且只有在添加的第一个布局中。代码如下:
add_ingredient.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.ingredient_quantity_layout, null);
// Add the new row before the add field button.
parentIngredientLayout.addView(rowView);
ImageButton removeChildIngredient = findViewById(R.id.remove_ingredient_btn);
removeChildIngredient.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
parentIngredientLayout.removeView((View) v.getParent());
}
});
}
});
【问题讨论】:
标签: android view onclicklistener layout-inflater