Android:在渲染之前测量视图的大小
我有一个 TextView,它显示更改的文本和运行时。我想使用 View.getLineCount() 方法来查看 TextView 占用了多少行并相应地执行不同的功能。问题是我需要确定 TextView 占用的行数,方法与需要知道它占用多少行的方法相同。我尝试在两次调用之间调用 View.invalidate() 但似乎没有解决任何问题。如果可能的话,我想在不渲染视图的情况下测量行数,但如果我必须渲染它,我也愿意这样做。如果这还不够具体,请告诉我,我会尽力更具体。谢谢!
I have a TextView that displays text that changes and run time. I want to use the View.getLineCount() method to see how many lines the TextView takes up and do different functions accordingly. The problem is I need to determine the number of lines the TextView takes up in the same method that needs to know how many line it takes up. I have tried calling View.invalidate() in between the two calls but that hasn't seemed to fix anything. I would like to measure the number of lines without rendering the view if possible but if I have to render it I would be open to doing that as well. Let me know if this is not specific enough and I will try to be more specific. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这实际上是 Android 中一个非常复杂的问题。如果您需要知道设置文本的时间(即在渲染视图之前或接近渲染视图之前),那么您唯一真正的选择是使用 StaticLayout。如果您可以等到接近渲染时间,则可以使用 viewTreeObserver:
onGlobalLayout 可以多次调用,有时(无论出于何种原因)我发现视图实际上尚未布局,因此您应该进行一些日志记录并查看如果你能找到一种方法来确保你得到的任何结果实际上都是有意义的(即行数> 0)。
StaticLayouts 是一个更复杂的替代方案,它应该能够为您提供视图的大小和行数。它们可能需要一些调整才能正常工作,并确保您使用要测量的视图中的绘制:
如果您愿意(或已经拥有)子类化 TextView,则可以覆盖 onSizeChanged 或 onMeasure 并尝试获取那里的行数。同样,与视图树观察器一样,有时可以在实际测量视图之前调用这些方法,因此您可能必须检查以确保在这些方法中获得的任何值都有意义。
This can actually be a really complex problem in Android. If you need to know at the time you set the text (ie before the view is rendered or near being rendered), you're only real option is to use StaticLayout. If you can wait until near render time, you can use a viewTreeObserver:
onGlobalLayout can be called multiple times and sometimes (for whatever reason) I've found that views aren't actually laid out yet, so you should do some logging and see if you can find a way to make sure that whatever result you get actually makes sense (ie a line count > 0).
StaticLayouts are a more complicated alternative that should be able to give you the size of your view and number of lines. They can require some tweaking to get to work properly, and make sure you use the paint from the view you're trying to measure:
If you're willing to (or already have) subclassed TextView, you can override onSizeChanged or onMeasure and try to get the number of lines there. Again, like with the view tree observer, sometimes those can be called before your view has actually been measured, so you may have to check to make sure whatever value you get in those methods make sense.