简体   繁体   English

OnWindowFocusChanged与OnCreate用于分配对象属性

[英]OnWindowFocusChanged vs OnCreate for assigning object properties

My question revolves around the onWindowFocusChanged method. 我的问题围绕onWindowFocusChanged方法。 I know that as a best practice, you should inflate your objects in the onCreate method. 我知道,作为最佳实践,您应该在onCreate方法中为对象充气。

What I'm wondering about is this: objects such as ImageViews are not completely rendered during the onCreate method. 我想知道的是:在onCreate方法期间,诸如ImageViews之类的对象未完全呈现。 So you use onWindowFocusChanged, which the Android documentation says is called once the activity render is complete. 因此,您可以使用onWindowFocusChanged,一旦活动渲染完成,Android文档便会调用该onWindowFocusChanged。 I have ImageView objects that I need to get the X and Y positions for and (because of varying screen sizes) I won't know exactly where they are positioned on the screen unless I use hard coded numbers, which I don't want to do. 我有ImageView对象,它们需要获取X和Y的位置,并且(由于屏幕尺寸的变化)除非使用硬编码数字,否则我将不知道它们在屏幕上的确切位置,我不想这样做。做。 I'll then assign margins for other ImageViews based on these X and Y numbers. 然后,我将基于这些X和Y数字为其他ImageView分配边距。 But if I have to wait until onWindowFocusChanged to get X and Y, it doesn't do me any good to set those numbers in onCreate method. 但是,如果我必须等到onWindowFocusChanged才能获取X和Y,那么在onCreate方法中设置这些数字对我没有任何好处。

So my question is - can I still set the properties of an ImageView inside of onWindowFocusChanged and have them re-rendered to their updated properties, or are the property values locked in because they've already been rendered? 所以我的问题是-我仍然可以在onWindowFocusChanged内设置ImageView的属性,并将它们重新呈现为更新后的属性,还是因为已经渲染了属性值而将其锁定?

Try by maintaining your View object inside the Activity class and calling postInvalidate() after the properties are set inside onWindowFocusChanged(). 通过在onWindowFocusChanged()中设置属性后,尝试将您的View对象维护在Activity类内,并调用postInvalidate()。 Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM