So basically I have activity with 10 edit texts and each of them has implemented this code pastes below:
editText.doAfterTextChanged
{
editText2.requestFocus()
}
and
editText2.setOnKeyListener { v, keyCode, event ->
when {
((keyCode == KeyEvent.KEYCODE_DEL) && (event.action == KeyEvent.ACTION_DOWN)) -> {
if (editText2.text.isNotEmpty())
{
editText2.text.clear()
}
else
{
editText.requestFocus()
}
return@setOnKeyListener true
}
else -> false
}
}
Each edit text has android:maxLength="1"
and I implement the above code in almost all of them. Is there a way that could save me some time if I need 30? I also want to have clean code to make it easier for someone to read it
CodePudding user response:
You can create a list of your views, and then iterate them to add these features.
If you iterate the indices, you can use the index to also get the previous and next neighbors to use in your listeners. At the beginning and end of the list we put null values for previous or next and then we can use ?.
null safe calls to ignore them in the listeners.
val editTexts = listOf(editText, editText2, editText3, /*...*/)
for (i in editTexts.indices) {
val previous = if (i == 0) null else editTexts[i - 1]
val current = editTexts[i]
val next = if (i == editTexts.size - 1) null else editTexts[i 1]
current.doAfterTextChanged { next?.requestFocus() }
current.setOnKeyListener { v, keyCode, event ->
when {
((keyCode == KeyEvent.KEYCODE_DEL) && (event.action == KeyEvent.ACTION_DOWN)) -> {
if (current.text.isNotEmpty()) {
current.text.clear()
} else {
previous?.requestFocus()
}
true
}
else -> false
}
}
}
If you name your views consistently, starting with editText1
, editText2
, and so on, then you could use getIdentifier
to generate your list without typing each name:
// if there are 30 views starting with editText1:
// In a fragment:
val editTexts = (1..30).map {
val id = requireContext().resources.getIdentifier("editText$it", "id", requireContext().packageName)
view.findViewById<TextView>(id)
}
// In an activity:
val editTexts = (1..30).map {
val id = resources.getIdentifier("editText$it", "id", packageName)
findViewById<TextView>(id)
}
CodePudding user response:
maybe this approache can help you.
You set the behavior of your Button TextView in the onClick and set every Boton or TextView with te OnclickListener.
class MainActivity : AppCompatActivity(), View.OnClickListener{
lateinit var button : Button
lateinit var button2 : Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button = findViewById(R.id.button1)
button.setOnClickListener(this)
button2 = findViewById(R.id.button2)
button2.setOnClickListener(this)
}
override fun onClick(view: View?) {
}
}