Android 片段事件侦听器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21179280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:06:26  来源:igfitidea点击:

Android fragment event listeners

androidfragmentlisteneractivity-lifecycle

提问by Chris

As i understand it, would it not be better to create a fragments event listeners in the fragments onCreate? If it is done in onCreateView it would have to be redone everytime the fragment comes back into view (onResume())? Would it make a difference where it is set?

据我了解,在片段 onCreate 中创建片段事件侦听器不是更好吗?如果它是在 onCreateView 中完成的,那么每次片段回到视图中时都必须重做(onResume())?它的设置位置会有所不同吗?

回答by Jitesh Upadhyay

1) yes it can be better

1)是的,它可以更好

2) yes you are correct, as event listener is initialised there than the process will be repeated here

2)是的,你是对的,因为事件监听器在那里初始化,而不是在这里重复这个过程

enter image description here

在此处输入图片说明

3) please have a close look at life-cycle method

3)请仔细看看生命周期方法

4)it always makes difference where you are using and when you are initializing.

4)它总是在您使用和初始化时有所不同。

回答by Srikanth

An event is set on a view and hence is restored when the view is restored. For example, lets say we set a listener on a button in a fragment that is created in onCreateView. If at some point of time, if the fragment is restored (without a call to onCreateView), the button is restored along with the listener that is set. The same goes for setting a text/background for a button - you don't have to reset the text/background each time the fragment is resumed.

事件在视图上设置,因此在视图恢复时恢复。例如,假设我们在 onCreateView 中创建的片段中的按钮上设置了一个侦听器。如果在某个时间点,如果片段被恢复(没有调用 onCreateView),按钮将与设置的侦听器一起恢复。为按钮设置文本/背景也是如此 - 您不必每次恢复片段时都重置文本/背景。