【发布时间】:2023-03-10 06:53:01
【问题描述】:
我正在使用仅接受数字作为输入类型的 TextEdit,并且我想在按下按钮时设置 TextEdit 的值。但是,我无法让它工作。
当我只做 textWithAmount.setText(balance),而 balance 很长时,我得到一条波浪线,说这不符合 setText 函数并且我无法运行我的代码。
当我将它转换为 Int (setText(balance.toInt()) 时,我收到以下错误:
android.content.res.Resources$NotFoundException: 字符串资源 ID #0x2710
当我将它转换为 String (setText(balance.toString()) 时,我收到以下错误:
java.lang.ClassCastException: android.text.SpannableStringBuilder 无法转换为 java.lang.Long
Kotlin 代码:
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" />
有人知道这个问题的解决方案吗?任何答案将不胜感激
编辑: 我刚刚意识到我在同一个 TextEdit 上也有一个 textChangedListener,当我填充它时可能会调用它。也许那里有问题:
textAmount.addTextChangedListener { text ->
val input : Long = text as Long
if(input > cash){
textAmount.setText(cash.toString())
}
}```
【问题讨论】:
-
你在使用
Spannable吗? -
@cutiko 不,我不是
-
balance.toString()不会转换为字符串。它通过转换输入 Long 创建一个新的 String 对象。我们必须查看更多关于此的代码才能知道出了什么问题。您发布的内容应该只是将字符串传递给setText,这样应该可以正常工作。您的错误表明您正在尝试将 SpannableStringBuilder 转换为 Long,这是您必须在代码的其他地方执行的操作。请显示您在其中放置as Long之类的代码 -
@Tenfour04 我刚刚注意到可能是什么问题;我在同一个 texfield 上也有一个 textchangedlistener,当我以编程方式填充 textedit 时可能会调用它。它的代码在这里:
textAmount.addTextChangedListener { text -> val input : Long = text as Long if(input > cash){ textAmount.setText(cash.toString()) } }
标签: android xml kotlin android-edittext settext