在运行时确定 Android 视图的大小 [英] Determining the size of an Android view at runtime

查看:25
本文介绍了在运行时确定 Android 视图的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在创建活动后将动画应用到我的 Android 应用程序中的视图.为此,我需要确定视图的当前大小,然后设置动画以从当前大小缩放到新大小.这部分必须在运行时完成,因为视图会根据用户的输入缩放到不同的大小.我的布局是用 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() 时.width 等,它们都返回 0.我也尝试在视图上手动调用 measure(),然后调用 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?

推荐答案

根据@maird 的建议,我通过子类化 ImageView 类并覆盖 onLayout().然后,我创建了一个观察者接口,我的 Activity 实现了该接口,并将对自身的引用传递给该类,这允许它在实际完成调整大小时告诉 Activity.

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.

这篇关于在运行时确定 Android 视图的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆