Two different approaches.
- If they are part of a big or complicated layout in a ScrollView, this is probably the one you should pick. Create a parent view for them, such as GridView or LinearLayout, in your XML layout for the Activity. You can add two or three EditTexts to this parent in your layout temporarily to figure out what layout params you want to give them to get the right look.
Then create another xml file to represent each individual EditText by itself, with the parameters it will have when added to the parent view. (You could alternatively skip this step and do all the EditText setup in Kotlin code, but that's a bit more complicated to get right.) This is just an example. You should use the layout parameters that make sense for what you're putting it in.
<?xml version="1.0" encoding="utf-8"?>
<EditText
android:id="@+id/editText"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:inputType="text"/>
Then in onCreate(), you can instantiate them in a List constructor, and add them to the parent at the same time. Use the LayoutInflater to do this. The layout ID is the one for the XML file of the single EditText. PAssing true as the third parameter adds the newly inflated view to the parent view group.
val parentView = binding.editTextsParent // or findViewById if not using view binding
val editTexts = List(numberOfEditTexts) {
layoutInflater.inflate(R.layout.single_edit_text, parentView, true)
}
And now you have a List of your EditTexts that you can use to grab data from them, or iterate to set up TextWatchers, etc.
- Use this if there are a lot of them or they are going to be the only thing on the screen. In this case, we would use a RecyclerView. There are tons of tutorials on RecyclerViews, so I won't explain exactly how it's done. But to apply a RecyclerView in this case, your backing list of data would be a List of Strings that is the same size as the number of EditTexts you want to create. The layout you create for each item to put in the RecyclerView.Adapter would have just an EditText in it. You would have to add a TextWatcher to each EditText that updates the values in the backing List as they are edited. This is so if an EditText is recycled (a new one scrolls onto the screen), you can update it with the text that the corresponding list item was last showing before it scrolled off the screen.