如何将 EditText 值添加到 Kotlin 中的 ArrayList?

How to add EditText values to an ArrayList in Kotlin?

我有十个 ExitText,我想将它的值添加到一个 ArrayList 中,然后将它们添加到 Firebase。

如何将值添加到 Kotlin 中的 ArrayList 中?

我知道这不是应该做的,但我只是在尝试,我一直在循环遍历并添加到数组中。我知道我可以使用 zipCodeList.add 添加,但我不知道如何遍历 EditText 并获取值。

fun createListOfZipCodes (): ArrayList<ZipCode>{
    
            zip_one=binding.etZipCodeOne.text.toString()
            zip_two=binding.etZipCodeTwo.text.toString()
            zip_three=binding.etZipCodeThree.text.toString()
            zip_four=binding.etZipCodeFour.text.toString()
            zip_five=binding.etZipCodeFive.text.toString()
            zip_six=binding.etZipCodeSix.text.toString()
            zip_seven=binding.etZipCodeSeven.text.toString()
            zip_eight=binding.etZipCodeEight.text.toString()
            zip_nine=binding.etZipCodeNine.text.toString()
            zip_ten=binding.etZipCodeTen.text.toString()
    
    /// I HAVE NO IDEA HOW TO LOOP THROUGH EACH EDIT TEXT AND GET THE VALUE.
    
            return zipCodeList
    
}

我正在寻找在 Kotlin 中执行此操作的答案。

谢谢。


编辑 2

class AssignZIPCodeActivity : AppCompatActivity() {
    
        private lateinit var binding:ActivityAssignZipcodeBinding
    
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            binding= ActivityAssignZipcodeBinding.inflate(layoutInflater)
            setContentView(binding.root)
            
            }
    
    }

编辑:

错误

    2021-07-02 21:08:30.525 21588-21588/com.trad E/RecyclerView: No adapter attached; skipping layout
2021-07-02 21:08:35.505 21588-21588/com.trad E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.trad, PID: 21588
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.trad/com.trad.ui.activities.AssignZIPCodeActivity}: kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3683)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3968)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:8512)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
     Caused by: kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized
        at com.trad.ui.activities.AssignZIPCodeActivity.<init>(AssignZIPCodeActivity.kt:18)
        at java.lang.Class.newInstance(Native Method)
        at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
        at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3671)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3968) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:246) 
        at android.app.ActivityThread.main(ActivityThread.java:8512) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130) 

完整的 Kotlin 代码。

    class AssignZIPCodeActivity : AppCompatActivity() {

    private lateinit var binding:ActivityAssignZipcodeBinding
    private lateinit var zipCodeList:ArrayList<String>

     val fields = listOf(
        binding.etZipCodeOne,
        binding.etZipCodeTwo,
        binding.etZipCodeThree,
        binding.etZipCodeFour,
        binding.etZipCodeFive,
        binding.etZipCodeSix,
        binding.etZipCodeSeven,
        binding.etZipCodeEight,
        binding.etZipCodeNine,
        binding.etZipCodeTen,
    )

    val zipCodes = createListOfZipCodes(fields)


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding= ActivityAssignZipcodeBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.btnAddZipCodes.setOnClickListener{
            createListOfZipCodes(fields)
//            Toast.makeText(this@AssignZIPCodeActivity,zipCodeList.toString(),Toast.LENGTH_SHORT).show()
        }
    }

以下是activity_assign_zipcode.xml.

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.activities.AssignZIPCodeActivity">

    <ScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        android:scrollbars="none">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">


            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/til_zip_code_one"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:hint="ZIP Code 1"
                android:textColorHint="@color/colorSecondaryText">

                <com.trad.utils.MSPEditText
                    android:id="@+id/et_zip_code_one"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number|numberDecimal"
                    android:padding="@dimen/et_padding"
                    android:textColor="@color/colorPrimaryText"
                    android:textSize="@dimen/et_textSize"/>
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/til_zip_code_two"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/til_zip_code_one"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:hint="ZIP Code 2"
                android:textColorHint="@color/colorSecondaryText">

                <com.trad.utils.MSPEditText
                    android:id="@+id/et_zip_code_two"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number|numberDecimal"
                    android:padding="@dimen/et_padding"
                    android:textColor="@color/colorPrimaryText"
                    android:textSize="@dimen/et_textSize" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/til_zip_code_three"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/til_zip_code_two"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:hint="ZIP Code 3"
                android:textColorHint="@color/colorSecondaryText">

                <com.trad.utils.MSPEditText
                    android:id="@+id/et_zip_code_three"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number|numberDecimal"
                    android:padding="@dimen/et_padding"
                    android:textColor="@color/colorPrimaryText"
                    android:textSize="@dimen/et_textSize" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/til_zip_code_four"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/til_zip_code_three"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:hint="ZIP Code 4"
                android:textColorHint="@color/colorSecondaryText">

                <com.trad.utils.MSPEditText
                    android:id="@+id/et_zip_code_four"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number|numberDecimal"
                    android:padding="@dimen/et_padding"
                    android:textColor="@color/colorPrimaryText"
                    android:textSize="@dimen/et_textSize" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/til_zip_code_five"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/til_zip_code_four"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:hint="ZIP Code 5"
                android:textColorHint="@color/colorSecondaryText">

                <com.trad.utils.MSPEditText
                    android:id="@+id/et_zip_code_five"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number|numberDecimal"
                    android:padding="@dimen/et_padding"
                    android:textColor="@color/colorPrimaryText"
                    android:textSize="@dimen/et_textSize" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/til_zip_code_six"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/til_zip_code_five"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:hint="ZIP Code 6"
                android:textColorHint="@color/colorSecondaryText">

                <com.trad.utils.MSPEditText
                    android:id="@+id/et_zip_code_six"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number|numberDecimal"
                    android:padding="@dimen/et_padding"
                    android:textColor="@color/colorPrimaryText"
                    android:textSize="@dimen/et_textSize" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/til_zip_code_seven"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/til_zip_code_six"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:hint="ZIP Code 7"
                android:textColorHint="@color/colorSecondaryText">

                <com.trad.utils.MSPEditText
                    android:id="@+id/et_zip_code_seven"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number|numberDecimal"
                    android:padding="@dimen/et_padding"
                    android:textColor="@color/colorPrimaryText"
                    android:textSize="@dimen/et_textSize" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/til_zip_code_eight"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/til_zip_code_seven"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:hint="ZIP Code 8"
                android:textColorHint="@color/colorSecondaryText">

                <com.trad.utils.MSPEditText
                    android:id="@+id/et_zip_code_eight"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number|numberDecimal"
                    android:padding="@dimen/et_padding"
                    android:textColor="@color/colorPrimaryText"
                    android:textSize="@dimen/et_textSize" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/til_zip_code_nine"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/til_zip_code_eight"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:hint="ZIP Code 9"
                android:textColorHint="@color/colorSecondaryText">

                <com.trad.utils.MSPEditText
                    android:id="@+id/et_zip_code_nine"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number|numberDecimal"
                    android:padding="@dimen/et_padding"
                    android:textColor="@color/colorPrimaryText"
                    android:textSize="@dimen/et_textSize" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/til_zip_code_ten"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/til_zip_code_nine"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:hint="ZIP Code 10"
                android:textColorHint="@color/colorSecondaryText">

                <com.trad.utils.MSPEditText
                    android:id="@+id/et_zip_code_ten"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text"
                    android:padding="@dimen/et_padding"
                    android:textColor="@color/colorPrimaryText"
                    android:textSize="@dimen/et_textSize" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.trad.utils.MSPButton
                android:id="@+id/btn_add_zip_codes"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginStart="16dp"
                android:layout_marginTop="30dp"
                android:layout_marginEnd="16dp"
                android:background="@drawable/button_background"
                android:foreground="?attr/selectableItemBackground"
                android:gravity="center"
                android:paddingTop="@dimen/btn_padding"
                android:paddingBottom="@dimen/btn_padding"
                android:text="@string/btn_lbl_submit"
                android:textColor="@android:color/white"
                android:textSize="@dimen/btn_textSize"
                android:layout_below="@id/til_zip_code_ten"/>
        </RelativeLayout>

    </ScrollView>

</RelativeLayout>

很难做得更好:

val fields = listOf(
        binding.etZipCodeOne,
        binding.etZipCodeTwo,
        binding.etZipCodeThree,
        binding.etZipCodeFour,
        binding.etZipCodeFive,
        binding.etZipCodeSix,
        binding.etZipCodeSeven,
        binding.etZipCodeEight,
        binding.etZipCodeNine,
        binding.etZipCodeTen,
)

val zipCodes = createListOfZipCodes(fields)

fun createListOfZipCodes(fields: List<EditText>): ArrayList<ZipCode> {
    val zipCodeList = mutableListOf<ZipCode>()
    for (filed in fields) {
        zipCodeList.add(filed.text.toString())
    }
    return zipCodeList
}

这与指出的不同。 OP 需要有一种更好的方法来将元素添加到数组中而不处理它们的 id。

因此,为包含 EditText 的 RelativeLayout 提供一个 ID:

    <RelativeLayout
        android:id="@+id/root"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

然后您可以遍历 RelativeLayout 的子项并找到 TextInputLayout。并重复查找 TextInputEditText

val list = arrayListOf<String>()

// Layout that has multiple TextInputLayouts
val root = findViewById<RelativeLayout>(R.id.root)

// Iterating over children of the RelativeLayout
for (item in 0..root.childCount) {
    val child = root.getChildAt(item)
    if (child is TextInputLayout) {
        val editText = (child.getChildAt(0) as FrameLayout).getChildAt(0)
        if (editText is TextInputEditText) list.add(editText.text.toString())
    }
}
Log.d(TAG, "onCreate: $list")

更新:

How can I write this as a function so that I can call it on a button click?

class AssignZIPCodeActivity : AppCompatActivity() {

    private lateinit var binding:ActivityAssignZipcodeBinding
    private lateinit var zipCodeList:ArrayList<String>


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding= ActivityAssignZipcodeBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        binding.btnAddZipCodes.setOnClickListener{
              zipCodeList = createListOfZipCodes()

//            Toast.makeText(this@AssignZIPCodeActivity,zipCodeList.toString(),Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun createListOfZipCodes(): ArrayList<String> {
    
        val list = arrayListOf<String>()

        // Layout that has multiple TextInputLayouts
        val root = findViewById<RelativeLayout>(R.id.root)

        // Iterating over children of the RelativeLayout
        for (item in 0..root.childCount) {
            val child = root.getChildAt(item)
            if (child is TextInputLayout) {
                val editText = (child.getChildAt(0) as FrameLayout).getChildAt(0)
                if (editText is com.trad.utils.MSPEditText) list.add(editText.text.toString())
            }
        }   
        return list
    }
    
}