我正在构建一个应用程序,用户需要填写一些数据才能发布一些内容,因此 fragment 由 EditText
组成、单选按钮和 Spinner
连同 RecyclerView
它动态呈现了一些包含 TextView
的子布局和 EditText
.
因此,当用户从 Spinner
中选择类别时, 与该类别相关的一些属性显示在 RecyclerView
中用户可以选择填写其中的一些内容。
我尝试使用回调和 TextWatcher
来实现此功能但我没有得到我想要的值。
回调
interface PropertiesCallback {
fun addProp(position: Int, title: String, value: String)
}
适配器
class PropertiesAdapter(private val propertiesCallback: PropertiesCallback)
: RecyclerView.Adapter<PropertiesAdapter.ViewHolder>() {
private var list = listOf<CategoriesAndSubcategoriesQuery.Property>()
fun setData(listOfProps: List<CategoriesAndSubcategoriesQuery.Property>) {
this.list = listOfProps
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.z_property_input, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int = list.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(list[position], position)
}
inner class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
private val label: TextView = view.findViewById(R.id.label)
private val input: EditText = view.findViewById(R.id.input)
fun bind(prop: CategoriesAndSubcategoriesQuery.Property, position: Int) {
label.text = prop.title()
prop.hint()?.let { input.hint = prop.hint() }
input.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
propertiesCallback.addProp(position, prop.title(), input.text.toString())
}
})
}
}
}
在 fragment 中
private var propertiesList = mutableListOf<CategoriesAndSubcategoriesQuery.Property>()
private var propertiesInputList = mutableListOf<ProductPropertiesInput>()
private fun setUpSubcategorySpinner() {
subcategoriesAdapter = ArrayAdapter(
this@AddProductFragment.context!!,
android.R.layout.simple_spinner_item,
subcategoriesList
)
//Subcategories
subcategoriesAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line)
subcategory_spinner.adapter = subcategoriesAdapter
subcategory_spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
subcategoryId = subcategoriesList[position].id()
//Adding properties
subcategoriesList[position].properties()?.let {
//Clear previous properties data of another subcategory.
propertiesInputList.clear()
propertiesList.clear()
propertiesList.addAll(it)
propertiesAdapter.setData(propertiesList)
propertiesAdapter.notifyDataSetChanged()
}
}
override fun onNothingSelected(parent: AdapterView<*>) {}
}
}
覆盖
override fun addProp(position: Int, title: String, value: String) {
val prop = ProductPropertiesInput
.builder()
.title(title)
.value(value)
.build()
propertiesInputList.add(prop)
//Log.d(TAG, "prop: ${prop.title()} : ${prop.value()}")
}
提交乐趣
private fun submitProduct() {
//Initializing properties.
val properties: Any
//The keys needed in final list.
val propertyKeys = propertiesList.map { it.title() }
//Removing objects which keys are not needed.
propertiesInputList.removeAll { it.title() !in propertyKeys }
Log.d(TAG, "propertiesInputList: $propertiesInputList")
//Removing duplicate and assign result in properties var.
properties = propertiesInputList
.distinctBy { it.title() }
Log.d(TAG, "properties: $properties")
for (prop in properties) {
Log.d(TAG, "properties , title: ${prop.title()}, value: ${prop.value()} ")
}
}
以上代码旨在作为。当用户在 EditText
之一中键入值时在 RecyclerView
该值将被分割并添加到一个对象中,该对象采用标题和值,然后添加到 propertiesInputList
.
问题 1: propertiesInputList
将有很多具有相同标题的重复对象,我认为最好的解决方案是使用 distinctBy
.
问题 2: 当用户填写一个数字 EditText
时这与我们说的category1
有关并改变主意并从 Spinner
中选择另一个类别. 不属于新选择类别的先前值保留在 propertiesInputList
中列表。所以我认为最好的解决方案是清除 propertiesInputList
并使用 removeAll
使用与类别相关的标题来过滤不需要的对象。
但现在我只得到用户类型的第一个字母。如果用户输入shoes,我得到s。看来distinctBy
返回第一个对象,但我想准确地获取用户输入的最后一个词,如果用户输入并删除了我想要空白的所有内容。
是否有更好的解决方案来处理这个问题?喜欢循环recyclerView
仅当用户按下提交而不是 TextWatcher
时?或者我应该修复哪个部分才能使其正常工作?
最佳答案
我不完全理解您要在这里实现的目标。 RecyclerView 中的 EditTexts 通常不是一个好主意,原因如下。
- 当 recyclerView 滚动时,您可能希望保留 用户为该特定字段/项目添加的文本并显示它 当用户向后滚动时正确。
- 当您将
TextWatcher
添加到 EditText 时,您还需要在回收 View 或再次绑定(bind) View 持有者时将其删除。否则,您最终会遇到多个听众,事情就会出错。
关于你的另一个问题,
But now I get only the first letter user types. If user types shoes I get s
这是设计使然。每次输入字符时,TextWatcher 都会发出事件。所以你会得到 s, sh, sho, shoe, shoes。因此您不能对这些数据采取行动,因为用户仍在向该字段添加内容。
所以,
您不知道用户何时停止向 EditText 添加文本(或者用户是否已完成)。您可以使用
debounce
之类的东西,但这很复杂。你应该给用户一个按钮。获取用户点击按钮时的值。我假设您在 RecyclerView 中有多个编辑文本。因此,您需要存储每个 edittext 的值,因为 recyclerview 将重新使用 View ,您将丢失数据。您可以在适配器的
onViewRecycled
回调中执行此操作。保留一个 id -> string 的映射,用于存储此数据并在 View 持有者绑定(bind)时检索。您也可以使用 TextWatcher,但您需要先将其分离,然后再附加一个新的或在
onViewRecycled
中。
更新:
如果我有这样的事情,我会使用带有垂直 LinearLayout 的 ScrollView(为简单起见)并根据需要添加 EditText。如果您想添加 TextWatcher,您需要某种稳定的 ID。
class EditTextContainer : LinearLayout {
private val views = mutableListOf<EditText>()
private val textWatchers = hashMapOf<Int, TextWatcher>()
... constructor and bunch of stuff
fun updateViews(items: List<Item>, textCallback: (id, text) -> Unit) {
// Remove text watchers
views.forEach { view ->
view.removeTextWatcher(textWatchers[view.id])
}
// More views than required
while (views.size > items.size) {
val view = views.removeAt(views.size-1)
removeView(view)
}
// Less views than required
while (view.size < items.size) {
val view = createView()
view.id = View.generateViewId()
addView(view, createParams()) // Add this view to the container
views.add(view)
}
// Update the views
items.forEachIndexed { index, item ->
val editText = views[item]
// Update your edittext.
addTextWatcher(editText, item.id, textCallback)
}
}
private fun createView(): EditText {
// Create new view using inflater or just constructor and return
}
private fun createParams(): LayoutParams {
// Create layout params for the new view
}
private fun addTextWatcher(view, itemId, textCallback) {
val watcher = create text watcher where it invokes textCallback with itemId
view.addTextWatcher(watcher)
textWatchers[view.id] = watcher
}
}
关于android - 从 RecyclerView 获取 EditTexts 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56265895/