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

#android #android-studio #kotlin

#Android #android-studio #kotlin

Вопрос:

Я хочу создать программу, в которой в какой-то момент пользователю придется добавлять некоторые школьные предметы в качестве входных данных. Я создал поле ввода (см. Изображение Ниже), где при нажатии кнопки «Добавить» под ним будет создано равное поле. Кнопка «Удалить» служит для удаления поля ввода, но должно быть хотя бы одно поле ввода.

Позже

Поскольку я новичок в разработке Android, я хотел бы знать, как это сделать. Я уже исследовал некоторые веб-сайты, но смог генерировать только отдельные элементы, такие как TextViews, используя addView :

 val relLay = findViewById<RelativeLayout>(R.id.relLay1)
val btnAdd = findViewById<Button>(R.id.btnAdd)
btnAdd.setOnClickListener{
    val tv = TextView(this)
    tv.text = "This is a text view"
    val params : RelativeLayout.LayoutParams = RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT)
    params.setMargins(10, pos, 10, 10)
    pos  = 50     // pos is a variable that was declared previously
    rellay.addView(tv)
}
  

Как мне сгенерировать эти элементы в группе? И, кроме того, после создания других подобных полей, когда пользователь нажимает «Готово», как мне прочитать данные всех созданных полей?

Мой input_activity.xml файл:

 <?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@ id/relLay1"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <ScrollView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >

        <RelativeLayout
                android:id="@ id/relLay2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">

            ...

            <!-- Title of the input field -->
            <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Add subject"
                    android:layout_below="@id/table1"
                    android:layout_marginTop="15dp"
                    android:layout_centerHorizontal="true"
                    android:textSize="36sp"
                    android:id="@ id/txtSubtitle2"/>

            <!-- LinearLayout that I want to be created
            every time the user clickes the button Add -->
            <LinearLayout
                    android:orientation="vertical"
                    android:id="@ id/linLay1"
                    android:layout_below="@id/txtSubtitle2"
                    android:layout_marginTop="15dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                <EditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:inputType="textPersonName"
                        android:layout_marginLeft="15dp"
                        android:layout_marginStart="15dp"
                        android:layout_marginRight="15dp"
                        android:layout_marginEnd="15dp"
                        android:ems="10"
                        android:id="@ id/edtSubjectNam"
                        android:hint="Subject name"/>
                <TextView
                        android:text="Days of the week"
                        android:layout_marginLeft="15dp"
                        android:layout_marginStart="15dp"
                        android:layout_marginRight="15dp"
                        android:layout_marginEnd="15dp"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:textSize="18sp"
                        android:id="@ id/string3"/>
                <CheckBox
                        android:text="Sunday"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="15dp"
                        android:layout_marginStart="15dp"
                        android:layout_marginRight="15dp"
                        android:layout_marginEnd="15dp"
                        android:id="@ id/checkSun"/>
                <CheckBox
                        android:text="Monday"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="15dp"
                        android:layout_marginStart="15dp"
                        android:layout_marginRight="15dp"
                        android:layout_marginEnd="15dp"
                        android:id="@ id/checkMon"/>
                <CheckBox
                        android:text="Tuesday"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="15dp"
                        android:layout_marginStart="15dp"
                        android:layout_marginRight="15dp"
                        android:layout_marginEnd="15dp"
                        android:id="@ id/checkTue"/>
                <CheckBox
                        android:text="Wednesday"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="15dp"
                        android:layout_marginStart="15dp"
                        android:layout_marginRight="15dp"
                        android:layout_marginEnd="15dp"
                        android:id="@ id/checkWed"/>
                <CheckBox
                        android:text="Thursday"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="15dp"
                        android:layout_marginStart="15dp"
                        android:layout_marginRight="15dp"
                        android:layout_marginEnd="15dp"
                        android:id="@ id/checkThu"/>
                <CheckBox
                        android:text="Friday"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="15dp"
                        android:layout_marginStart="15dp"
                        android:layout_marginRight="15dp"
                        android:layout_marginEnd="15dp"
                        android:id="@ id/checkFri"/>
                <CheckBox
                        android:text="Saturday"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="15dp"
                        android:layout_marginStart="15dp"
                        android:layout_marginRight="15dp"
                        android:layout_marginEnd="15dp"
                        android:id="@ id/checkSat"/>

                <!-- LinearLayout of the buttons Done, Remove and Add -->
                <LinearLayout
                        android:orientation="horizontal"
                        android:layout_marginLeft="15dp"
                        android:layout_marginStart="15dp"
                        android:layout_marginRight="15dp"
                        android:layout_marginEnd="15dp"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent">
                    <Button
                            android:text="Done"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"  
                            android:id="@ id/btnDone"
                            android:layout_weight="1"/>
                    <Button
                            android:text="Add"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content" 
                            android:id="@ id/btnAdd"
                            android:layout_weight="1"/>
                    <Button
                            android:text="Remove"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content" 
                            android:id="@ id/btnRem"
                            android:layout_weight="1"/>
                </LinearLayout>


            </LinearLayout>
        </RelativeLayout>
    </ScrollView>
</RelativeLayout>
  

Мой код в Kotlin ( InputActivity.kt ) по-прежнему пуст, потому что я не мог сделать очень много. Любая помощь очень, очень приветствуется. Я также хотел бы получить некоторую помощь от того, как будет выглядеть код кнопки «Удалить», но меня больше всего беспокоит кнопка «Добавить».

Ответ №1:

Итак, что вы хотели бы сделать, это создать свой собственный файл макета только с этим представлением. Затем вы бы раздули представление и добавили его в родительское представление

  public View appendView(Activity activity) {
    LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    @SuppressLint("InflateParams") View view = inflater.inflate(R.layout.NAME_OF_YOUR_LAYOUT_FILE, null);
    LinearLayout parentLayout = activity.findViewById(R.id.YOUR_CONTAINER);
    parentLayout.addView(view);
}
  

Удалить было бы то же самое, но вместо addView вы бы сделали remove view. Возможно, вы захотите добавить анимацию для затухания или установить для представления значение animateLayout

Чтобы прочитать данные, просто выполните view.findViewById(R.id.FIELD), затем извлеките из него соответствующее значение и сохраните его. Возможно, вы захотите создать для него класс