【发布时间】:2020-11-12 01:09:18
【问题描述】:
当用户单击添加按钮时,我试图将新文本从 EditText 添加到数组中。 到目前为止,我已经从我的字符串文件中获得了硬编码文本,但是我希望能够在用户在 edittext 字段中键入它并按下添加按钮时添加新类别
这是我的课:
package com.example.myapplication
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.Model.MyModel
import com.example.myapplication.adapters.Category
class Profile : AppCompatActivity() {
lateinit var category: EditText
lateinit var add: Button
lateinit var categoryList: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_profile)
category = findViewById<EditText>(R.id.add_category)
add = findViewById<Button>(R.id.add_button)
//Set Recycler view
val categoryModelArrayList = populateList()
val recyclerView = findViewById<RecyclerView>(R.id.categoryLists)
val layoutManager = LinearLayoutManager(this)
recyclerView.layoutManager = layoutManager
val adapter = Category(categoryModelArrayList)
recyclerView.adapter = adapter
add.setOnClickListener {
val newCategory = category.text.toString().trim()
val isValid = validateCategory(newCategory)
if (isValid) {
dismissKeyBoard()
Toast.makeText(this, "$newCategory has been added to your list of following", Toast.LENGTH_LONG).show()
//Need to add $newCategory to the following list when the user clicks on the add button
}
}
}
private fun populateList() : ArrayList<MyModel> {
val list = ArrayList<MyModel>()
val categoryList = arrayOf(R.string.app_name, R.string.bottom_sheet_behavior, R.string.saved_articles)
val size = categoryList.size
for (i in categoryList.indices) {
val categoryModel = MyModel()
categoryModel.setCategories(getString(categoryList[i]))
list.add(categoryModel)
}
return list
}
private fun validateCategory(newCategory:String): Boolean {
if(newCategory.isEmpty()) {
category.setError("Category is required")
return false
}
return true
}
private fun dismissKeyBoard() {
val view = this.currentFocus
if (view != null) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
}
所以因为我只是使用我的应用程序的字符串文件中存在的字符串,但是我希望能够在用户按下添加按钮时添加新字符串,但是当我尝试添加新字符串时它说它需要一个Int 而不是 String,我不知道为什么
如何向这个数组添加新字符串?
【问题讨论】:
标签: android kotlin android-recyclerview