[英]how to implement onRetainNonConfigurationInstance
i made a media player in android it's working great but when i change the screen orientation, the activity is being restarted i know that this question was already asked on stackoverflow several times but none of the answers helped me. 我在Android中制作了一个媒体播放器,它工作得很好但是当我改变屏幕方向时,活动正在重新启动我知道这个问题已经在stackoverflow上被问了好几次,但没有一个答案对我有帮助。 i think i should use: onRetainNonConfigurationInstance
我想我应该使用:onRetainNonConfigurationInstance
@Override
public Object onRetainNonConfigurationInstance() { ... }
but i didn't know the correct way to implement it so if someone could give me a tutorial or an implicit example i would be grateful 但我不知道实现它的正确方法,所以如果有人能给我一个教程或一个隐含的例子,我将不胜感激
I believe that onRetainNonConfigurationInstance()
is deprecated. 我相信
onRetainNonConfigurationInstance()
已被弃用。 It will tell you to use Fragments
instead. 它会告诉你改为使用
Fragments
。 Here is a link to the Fragment
documentation. 这是
Fragment
文档的链接。 Basically, you will put your UI and data into a custom Fragment
, then use the FragmentManager
to store an instance of your Fragment
. 基本上,你会把你的UI和数据集成到一个自定义的
Fragment
,然后用FragmentManager
存储您的实例Fragment
。 Then, when the activity restarts, you can fetch your Fragment
and reposition as needed. 然后,当活动重新启动时,您可以根据需要获取
Fragment
并重新定位。
Never mind that it's deprectated, it works fine. 没关系它已经被删除了,它运作正常。 Simplest would be:
最简单的是:
public Object onRetainNonConfigurationInstance() {
return this;
}
Then in YourActivity
's onCreate()
然后在
YourActivity
的onCreate()
public void onCreate(Bundle savedState)
{
YourActivity prevActivity = (YourActivity)getLastNonConfigurationInstance();
if(prevActivity!= null) {
// So the orientation did change
// Restore some field for example
this.myValue = prevActivity.myValue;
}
}
In my media player, in order not to re-create MediaPlayer completely, I did the following: 在我的媒体播放器中,为了不完全重新创建MediaPlayer,我做了以下事情:
1) In AndroidManifest.xml added 1)在AndroidManifest.xml中添加
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize">
2) Inside the MainActivity added 2)在MainActivity内部添加
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setSize(mVideoWidth, mVideoHeight);
}
I hope this helps someone. 我希望这可以帮助别人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.