So I am having issues finding a Kotlin way to clear a edit number field when the input is selected to enter a number.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//MyCode
val submitButton: Button = findViewById(R.id.submit)
var quarterQuan: EditText = findViewById(R.id.quarterInput)
var dimeQuan: EditText = findViewById(R.id.dimeInput)
val quarterEditTextValue = quarterQuan.text.toString().toFloat()
val dimeEditTextValue = dimeQuan.text.toString().toFloat()
val dime = Dime()
val quarter= Quarter()
var quarterTotal = quarter.quarterVal*quarterEditTextValue
var dimeTotal = dime.dimeVal*dimeEditTextValue
var cashTotal = dimeTotal + quarterTotal
submitButton.setOnClickListener{
var resultTextViewLabel: TextView = findViewById(R.id.textResult)
resultTextViewLabel.text = cashTotal.toString()
}
}
}
I tried to do something to this effect with no success….
quarterQuan.setOnClickListener{
editText.getText().clear();
}
4
Answers
An easy and uncomplicated way to clear the textview is by setting the text to an emty string:
in
onCreate
scope:first define a
val
(E.g. edTex) from yourEditText
(E.g. editTextU)then write a listener for it, to call
cleartext()
function.Create
toEditable()
function for theString
class.and write
cleartext()
function.came here looking for how to do this. I tried FrozenAssassine’s answer, and it worked. I then thought about how, as I am teaching myself Kotlin and Android Studio, I have been taught to use the string resource file for strings to make them reusable.
I am writing a Guess My Number game to see how well I am understanding what I have learned so far. I have two different views: a TextView and an EditText. I decided to try setting an empty string in the string resource file that I could use in both places, and it worked.
In strings.xml:
In MainActivity.kt the TextView is to display how many guesses the player has made, and the EditText is for the player’s guess. The lines of code that clear them when the activity is reset for a new game:
This worked. Thanks for the help in figuring this out everyone 🙂
Edit text clearing method for Edittext field
Let we have
var quarterQuan: EditText = findViewById(R.id.quarterInput)
we want to clear this field. So we need to do something like this in kotlin
#We can do for every edittext field like this