在 Android 项目中使用 EditText.toString() 方法获取奇怪的文本。为什么?
我对 EditText 对象的理解似乎存在根本差距。我有一个带有单个 EditText 对象的 Activity+Layout 。在 EditText 对象中输入几个字符并按 Enter 键后,我在 onKey() 侦听器中检索文本。当我使用 toString() 方法检索文本时,我得到一个奇怪的字符串,例如:
android.widget.EditText@43749ff0
尽管事实上 EditText.mText 属性确实显示了我在测试期间输入的字符串“123”。为什么 toString() 返回不同的结果并且似乎是某种“未初始化”值?如何获取 mText 属性中当前所需的字符串以及那个奇怪的值是什么?
——罗施勒
I appear to have a fundamental gap in my understanding of an EditText object. I have an Activity+Layout with a single EditText object. After I type a few characters into the EditText object and hit the Enter key, I retrieve the text in my onKey() listener. When I use the toString() method to retrieve the text I get back a weird string like:
android.widget.EditText@43749ff0
Despite the fact the EditText.mText property does show the string I entered, "123" during my tests. Why is toString() returning a different result and what appears to be some kind of "uninitalize" value? How do I get the desired string currently in the mText property and what is that strange value?
-- roschler
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
浏览一下 API,建议您应该使用
getText()
方法。 toString() 是一个通用方法,适用于 Object 及其所有子类(即,据我所知,所有不是基元的东西)。它通常会被覆盖以提供更有用的字符串,但默认情况下,它会报告与您发布的内容类似的内容 - 稀疏描述和对象的哈希码。需要明确的是, API< /a> 将toString()
定义为:Passing glance at the API suggests you should use the
getText()
method.toString()
is a general method that applies toObject
and all its subclasses (i.e., everything that isn't a primitive, to my knowledge). It's often overridden to supply more useful strings, but by default, it reports something just like what you posted - a sparse description and the object's hashcode. To be clear, the API definestoString()
as:您不能对此使用“toString”方法,请改用“getText().toString()”。
You can't use the 'toString'-method on this, use 'getText().toString()' in stead.
您正在对视图对象调用 toString(),该对象可能没有定义 toString()。
我相信你想这样称呼:
editText.getText().toString()
You are calling toString() on a View Object, which probably does not have a toString() defined.
I believe you want to call this:
editText.getText().toString()
尝试
EditText.getText().toString()
Try
EditText.getText().toString()
花点时间阅读 java API: http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#toString%28%29
Take a moment to read the java API: http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#toString%28%29