Добавление EditText динамически нажатием кнопки - PullRequest
1 голос
/ 22 марта 2019

Я хочу добавить представление EditText «ингредиент» рядом с представлением EditText «количество», нажав кнопку «Добавить». Вот начальный код макета:

<LinearLayout android:id="@+id/ingredients_line_layout"
    android:layout_below="@+id/title_line_layout"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/layout_margin"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <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" />

    <EditText
        android:hint="@string/quantity"
        android:id="@+id/quantityField"
        android:inputType="number"
        android:layout_height="match_parent"
        android:layout_margin="@dimen/boxes_margin"
        android:layout_width="wrap_content" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/add_ingredient_btn"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/boxes_margin"
        android:layout_width="wrap_content"
        android:text="@string/add"
        app:icon="@drawable/ic_add_ingr_btn" />

</LinearLayout>

Как я могу реализовать метод onClick для кнопки в соответствующем упражнении?

Ответы [ 3 ]

1 голос
/ 22 марта 2019
  1. Вам необходимо установить OnClickListener для кнопки «Добавить»;
  2. Создать представление, которое вы хотите добавить;
  3. Найти ingredients_line_layout макет и добавить свой вид к нему.

См. Код ниже:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);
    View button = findViewById(R.id.add_ingredient_btn);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ViewGroup layout = (ViewGroup) findViewById(R.id.ingredients_line_layout);
            EditText ingredient = new EditText(YourActivity.this);
            ingredient.setHint(R.string.ingredients);
            layout.addView(ingredient, 1);
        }
    });
}
0 голосов
/ 22 марта 2019
EditText etIngredient = new EditText(context); // pass Context here
etIngredient.setLayoutParams(new LayoutParams(..., ...)); // two Arguments such as LayoutParams.WRAP_CONTENT
layout.addView(etIngredient);

Возможно, вы захотите добавить веса к макету, удерживая editText соответственно, если рядом есть два текста редактирования.

0 голосов
/ 22 марта 2019

Шаг 1: Запишите все представления в XML-файл и скройте «ингредиент» EditText

<LinearLayout android:id="@+id/ingredients_line_layout"
    android:layout_below="@+id/title_line_layout"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/layout_margin"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <EditText
        android:hint="@string/quantity"
        android:id="@+id/quantityField"
        android:inputType="number"
        android:layout_height="match_parent"
        android:layout_margin="@dimen/boxes_margin"
        android:layout_width="wrap_content" />

    <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:visibility="gone"
        android:inputType="text" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/add_ingredient_btn"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/boxes_margin"
        android:layout_width="wrap_content"
        android:text="@string/add"
        app:icon="@drawable/ic_add_ingr_btn" />

</LinearLayout>

Шаг 2: Зарегистрировать прослушивателя при нажатии на кнопку добавления.

addIngredientBtn.setOnClickListener(this);

Шаг 3: Видимый «ингредиент» при нажатии кнопки

@Override
public void onClick(View v) {
    ingredientsField.setVisibility(View.VISIBLE);
}

Таким образом, вы можете динамически добавлять EditText.

...