Android Edittext:在 Activity 的 onCreate() 中获取 LineCount
如何在活动的 onCreate() 方法中执行 Edittext 的 getLineCount() 操作,更改 Edittext 的文本,如下所示:
@override
public void onCreate(Bundle savedInstanceState){
myEditText.setText("EXAMPLE");
myEditText.getLineCount();
}
因为视图尚未绘制, getLineCount() 将始终返回 0。有没有办法解决这个问题?谢谢!
How can I do getLineCount() of an Edittext in the onCreate() method of an activity, having changed the Edittext's text, like the following:
@override
public void onCreate(Bundle savedInstanceState){
myEditText.setText("EXAMPLE");
myEditText.getLineCount();
}
Because the view has not been drawn yet getLineCount() will always return 0. Is there a way to get around this problem? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
呃,到处都是 UI 的问题。
您可以使用处理程序。您将发布一个 Runnable 来获取行数并继续处理。
Ugh, it's a problem with UI everywhere.
You can use a Handler. You'll post a Runnable that will get the line count and continue the processing.
这绝对是一种痛苦。就我而言,我不需要编辑,所以我使用
TextView
但看到EditText
派生自TextView
你应该能够使用同样的方法。我对TextView
进行了子类化并实现了onSizeChanged
来调用一个新的侦听器,我将其称为OnSizeChangedListener
。在侦听器中,您可以调用getLineCount()
并获取有效结果。TextView
:This is definitely a pain. In my case I didn't need editing, so I worked with
TextView
but seeing asEditText
derives fromTextView
you should be able to use the same approach. I subclassedTextView
and implementedonSizeChanged
to call a new listener which I calledOnSizeChangedListener
. In the listener you can callgetLineCount()
with valid results.The
TextView
:非常感谢最后的回答,对我很有帮助!
作为贡献,我想添加将注册到 SizeChangeNotifyingTextView 钩子的侦听器接口的代码(可以添加到 SizeChangeNotifyingTextView 类中):
最后,要注册侦听器,您可以这样做:
Thanks a lot for the last answer, it was very helpful to me!
As a contribution, I would like to add the code of the listener interface that will be registered to the SizeChangeNotifyingTextView's hook (which can be added inside the SizeChangeNotifyingTextView class):
Finally, to register a listener, you can do it this way: