I am using a TextEdit that only accepts numbers as input type and I would like to set the value of the TextEdit when a button is pressed. However, I can't get this to work.
When I just do textWithAmount.setText(balance), with balance being a long, I get a squiggly line saying that this doesn't conform the setText function and I can't run my code.
When I cast it to Int (setText(balance.toInt()), I get the following error:
android.content.res.Resources$NotFoundException: String resource ID #0x2710
When I cast it to String (setText(balance.toString()), I get the following error:
java.lang.ClassCastException: android.text.SpannableStringBuilder cannot be cast to java.lang.Long
Kotlin Code:
val buttonAll = findViewById<Button>(R.id.buttonWithAll)
var balance : Long = 0
buttonAll.setOnClickListener{
textAmount.setText(balance.toInt())
}
XML:
<EditText
android:id="@+id/textWithAmount"
android:layout_width="228dp"
android:layout_height="68dp"
android:layout_marginStart="16dp"
android:layout_marginTop="10dp"
android:ems="100"
android:importantForAutofill="no"
android:inputType="number"
app:layout_constraintEnd_toStartOf="@+id/buttonWithAll"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView4" />
<Button
android:id="@+id/buttonWithAll"
android:layout_width="68dp"
android:layout_height="68dp"
android:layout_marginEnd="9dp"
android:text="@string/all"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/textWithAmount"
app:layout_constraintTop_toTopOf="@+id/textWithAmount" />
Does anyone know a solution to this? Any answers would be appreciated
Edit: I just realized I also have a textChangedListener on the same TextEdit which is probably called when I fill it. Maybe something is wrong there:
textAmount.addTextChangedListener { text ->
val input : Long = text as Long
if(input > cash){
textAmount.setText(cash.toString())
}
}```
Spannablein any sort?balance.toString()doesn't cast to a String. It creates a new String object by converting the input Long. We'll have to see more of your code about this to know what went wrong. What you posted should just be passing a String tosetTextso that should work fine. Your error says you're trying to cast SpannableStringBuilder to a Long, which is something you must be doing elsewhere in your code. Please show the code where you have put something likeas LongtextAmount.addTextChangedListener { text -> val input : Long = text as Long if(input > cash){ textAmount.setText(cash.toString()) } }