java - 通过括号转换为字符串会导致 Android 崩溃

标签 java android string casting textview

我知道如何使用 toString() 从 TextView 获取字符串,但我想了解为什么如果我通过括号将 TextView 的文本转换为字符串,它会导致 Android 在运行时崩溃?

例如“String text = (String)((TextView)findViewById(R.id.myTextViewId)).getText();”

最佳答案

这是因为 getText() 返回 CharSequence(在某些情况下,您可以将其转换为 SpannableEditable cases) 不能直接转换为 string

使用 toString() 可以转换为 string 类。

来自 android 开发者文档:

public CharSequence getText ()

Return the text the TextView is displaying. If setText() was called with an argument of BufferType.SPANNABLE or BufferType.EDITABLE, you can cast the return value from this method to Spannable or Editable, respectively. Note: The content of the return value should not be modified. If you want a modifiable one, you should make your own copy first.

来源:http://developer.android.com/reference/android/widget/TextView.html

关于java - 通过括号转换为字符串会导致 Android 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19565045/

相关文章:

java - 不带数据类型的 Sencha GXT 组合框

java - 登录后在抽屉导航中显示电子邮件

java - RxJava。运营商在哪里?

java - Spring Boot 2.0 中的 EmbeddedServletContainerCustomizer

java - Play 中的 bindFromRequest 问题!框架 2.3

android - 在 Android 中发布新版本时如何删除旧的应用程序文件?

android - 由于 View Holder,Adapter 出现空指针异常

c++ - 类中的 ofstream - 试图引用已删除的函数

ios - Swift 根据不同的值连接字符串

javascript - 反转字符串首字母大写?JavaScript