【问题标题】:Passing an EditText Object and EditText.setText() throw Exception传递一个 EditText 对象和 EditText.setText() 抛出异常
【发布时间】:2016-05-20 12:21:50
【问题描述】:

我有一个实现以下功能的 Activity:

    public class SettingsActivity extends Activity {
         public void setText(EditText txtBox,String strText){
             txtBox.setText(strText);
         }
        public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.settings);
             EditText txtEdit = (EditText)findViewById(R.id.txtEdit);
             setText(txtEdit,"String");
             ...
        }

所以我试图将一个 EditText 对象传递给 setText 函数,然后调用 txtBox.setText() 函数。但这会引发以下异常:

android.content.res.Resources$NotFoundException: String resource ID #0x0

但是,当在onCreate() 中调用txtEdit.setText() 函数时,效果非常好。

编辑:函数 setText 是一个简化,我实际上传递了一个自定义类 a 的对象 a,然后称为 txtBox.setText(object.value),它(错误地)实际上是一个整数,而不是一个字符串。传递字符串修复了错误。给您带来的不便,我深表歉意。

【问题讨论】:

  • 清理/重建项目?我的意思是在你的代码中一切看起来都很好..
  • 是的!..我在我身边测试了你的代码...一切正常
  • 在我之前的回答中...我以为您在 setText() 方法中使用了相同的 Edittext
  • 您确定要传递字符串参数吗?当您将 int 0 传递给 setText 时会弹出此错误,该错误会尝试从字符串资源加载字符串。
  • 你的布局文件中有id txtEdit 吗?

标签: android android-activity android-edittext


【解决方案1】:

我才意识到,其实我并没有传递一个字符串参数。就像@Lubos Horacek 描述的那样,当您将 int 传递给 setText 时会引发异常。转换参数修复了错误。

【讨论】:

  • 但是在您共享的代码中,您将“String”作为参数传递,它是 String dude。
【解决方案2】:

可能是你的id在布局文件中不存在

【讨论】:

  • 这会带来空指针异常,因为 findViewById 在这种情况下返回 null。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多