在运行时间确定一个Android视图大小视图、大小、时间、Android

2023-09-12 00:09:47 作者:山雨欲来风满楼

我想创建我的活动后的动画应用到一个视图在我的Andr​​oid应用程序。要做到这一点,我需要确定视图的当前大小,然后设置动画从当前大小为新的大小规模。这部分必须做到在运行时,由于视图扩展到取决于来自用户的输入不同的大小。我的布局在XML定义的。

I am trying to apply an animation to a view in my Android app after my activity is created. To do this, I need to determine the current size of the view, and then set up an animation to scale from the current size to the new size. This part must be done at runtime, since the view scales to different sizes depending on input from the user. My layout is defined in XML.

这似乎是一件容易的事,而且有很多关于这虽然其中没有解决我的问题,明明那么问题。因此,也许我失去了一些东西明显。我得到一个处理我的观点是:

This seems like an easy task, and there are lots of SO questions regarding this though none which solved my problem, obviously. So perhaps I am missing something obvious. I get a handle to my view by:

ImageView myView = (ImageView)getWindow().findViewById(R.id.MyViewID);

这工作得很好,但打电话时的getWidth()的getHeight() getMeasuredWidth() getLayoutParams()。宽度等,它们都返回0。我也尝试过手动调用措施()的观点,随后通过调用 getMeasuredWidth(),但没有任何效果。

This works fine, but when calling getWidth(), getHeight(), getMeasuredWidth(), getLayoutParams().width, etc., they all return 0. I have also tried manually calling measure() on the view followed by a call to getMeasuredWidth(), but that has no effect.

我试图调用这些方法和检查对象中的调试器在我活动的的onCreate() onPostCreate()。我怎样才能找出这一观点的确切尺寸在运行时?

I have tried calling these methods and inspecting the object in the debugger in my activity's onCreate() and in onPostCreate(). How can I figure out the exact dimensions of this view at runtime?

推荐答案

根据@ mbaird的建议,我找到了一个可行的解决方案通过继承的ImageView 类并覆盖 onLayout()。然后,我创建了一个观察者的接口,我的活动实施并通过了对自身的引用的类,这使它能够告诉活动时,它实际完成上浆。

Based on @mbaird's advice, I found a workable solution by subclassing the ImageView class and overriding onLayout(). I then created an observer interface which my activity implemented and passed a reference to itself to the class, which allowed it to tell the activity when it was actually finished sizing.

我不是100%确信,这是最好的解决方法(因此我没有标记这个答案是正确的,只是还没有),但它确实工作,并根据文档是第一次,当人们可以找到的实际大小景色。

I'm not 100% convinced that this is the best solution (hence my not marking this answer as correct just yet), but it does work and according to the documentation is the first time when one can find the actual size of a view.