Android的活动刷新在旋转 [英] Android Activity Refreshing On Rotation

查看:124
本文介绍了Android的活动刷新在旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名经验丰富的.NET开发,但是这是我的第一个Android应用程序,它的驾驶我坚果!

这是一个倒计时器工作正常,但是当你旋转屏幕就重新初始化该归零的活动,停止倒计时。

这是我的尝试; 我摆脱了CountDownTimer对象,而是创建了一个类的内部到扩展的AsyncTask所以它运行在一个单独的线程...没有变化的活动。 我想作为一个内部类它被重新初始化与该活动。

下面是我的尝试下一个; 我做了类外部之一。该活动通过它的上下文的类和onProgressUpdate和放大器; onPostExecute上更新活动的用户界面中上下文中运行的公共职能。 再次,这正常工作,直到你旋转...... Aaaargh!

不过,我发现,异步类仍在运行,但用户界面不会改变,因为(我认为)的活动现在有一个不同的背景下一个异步类具有参考。

所以这就是我。每个解决方案解决一个问题:放大器;创建另一个。 我是否需要以某种方式维持的背景下还是我开始追逐自己的尾巴?

任何帮助将感激AP preciated!

钽。 巴里

解决方案
  

不过,我发现,异步类仍在运行,但用户界面不会改变,因为(我认为)的活动现在有一个不同的背景下一个异步类具有参考。

尼斯猜测。你必须处理活动的整个生命周期,如果你想保持计算的数据,因为当你旋转设备,该活动是越来越从而重新的onCreate( )获取调用的节省了previous计算的数据。你必须重写的onSaveInstanceState(包savedInstanceState) onRestoreInstanceState()为了节省您的计算。看看在活动的生命周期文档和的雷托•迈耶的回答,我认为这将解决您的问题。

I'm an experienced .NET dev, but this is my first Android app and it's driving me nuts!

It's a countdown timer which works fine, but when you rotate the screen it reinitialised the activity which zeroed and stopped the count down.

This is what I tried; I got rid of the CountDownTimer object and instead created a class internal to the activity which extended AsyncTask so it ran on a separate thread... No change. I figured being an internal class it's being reinitialised with the activity.

Here's what I tried next; I made the class an external one. The Activity passes its Context to the class and the onProgressUpdate & onPostExecute run public functions on the context to update the activity's UI. Again, this works fine until you rotate it... Aaaargh!

However, I discovered that the async class is still running but the UI doesn't change because (I think) the activity now has a different context to the one the async class has reference to.

So that's where I am. Each solution fixes one problem & creates another. Do I need to somehow maintain the context or am I starting to chase my own tail?

Any help will be gratefully appreciated!

Ta. Barry

解决方案

However, I discovered that the async class is still running but the UI doesn't change because (I think) the activity now has a different context to the one the async class has reference to.

Nice guess. You have to handle the Activity's lifecycle, if you want to keep the computed data since whenever you rotate the device, the activity is getting recreated thus onCreate() is getting called without saving the previous computed data. You have to override onSaveInstanceState(Bundle savedInstanceState) and onRestoreInstanceState() in order to save your computations. Take a look at the Activity's LifeCycle documentation and Reto Meier's answer, I think it will solve your problem.

这篇关于Android的活动刷新在旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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