通过一个活动的引用到另一个活动 [英] Pass reference of one Activity to another Activity

查看:192
本文介绍了通过一个活动的引用到另一个活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用意图传递活动之间的一些价值观。 不过,如果我想整个活动传递到另一个活动,我认为这是不好的做法。 是否有另一种方式来做到这一点?

I know that I can pass some values between Activities using intent. However, if I want to pass whole Activity to another Activity I think it is not good approach. Is there another way to do that?

我设置的活动中,我改变了一些颜色。所以,当我回到我的主要活动,我想应用这些颜色。要做到这一点,我需要访问MainActivity领域后,我改变颜色值,所以里面的preferenceActivity。换句话说,我想有机会获得由preferenceActivity类主要活动领域。任何想法?

I have Settings Activity in which I am changing some Colors. So after I come back to my Main Activity I would like to apply those colors. To do this, I need access to MainActivity fields after I change Color value, so inside PreferenceActivity. In other words, I want to have access to Main activity fields from PreferenceActivity class. Any ideas?

推荐答案

您应该使用共享preference ,然后访问,在你的主要活动。我建议你​​读了在 http://developer.android.com/guide/topics /ui/settings.html 因为它看起来像你实现你的设置活动不正确。你可能是特别感兴趣的部分是在读preferences部分。不过,我强烈建议你仔细阅读了整个事情,然后实现你的设置的正确方法。

You should be using a SharedPreference and then accessing that in your main activity. I recommend you reading up at http://developer.android.com/guide/topics/ui/settings.html because it seems like you are implementing your settings activity incorrectly. The part you might be specifically interested in is the "Read Preferences" section. However, I strongly suggest you read through the whole thing and then implement your settings the proper way.

与3种不同的方式(即我能想到的)更新答案:

Updated answer with the 3 different ways (that I can think of):

1),使用启动preference活动 startActivityForResult(),然后在 onActivityResult()访问在共享preference 键,让你的必要的修改。 查看 这里

1) Start your preference activity using startActivityForResult(), then in your onActivityResult() access the SharedPreference and make your necessary changes. See here

2)注册一个共享preferenceChangeListener 您MainActivity,当任何变化发生在你的共享preference将被称为查看 <一个href="http://stackoverflow.com/questions/2542938/shared$p$pferences-onshared$p$pferencechangelistener-not-being-called-consistently/3104265#3104265">here 进行了详细的讨论。同时看到我的初步回应。

2) Register a SharedPreferenceChangeListener with your MainActivity, which will be called when any changes happen to your SharedPreference. See here for a detailed discussion. Also see my initial response.

3)在你的MainActivity的 onResume(),进入共享preference 键,然后进行更改那里。我不喜欢这种方法,因为你会被搞乱 onResume()有更多的逻辑,你也可能必须有一个保持变量的状态跟踪一个变量,你有兴趣

3) In your MainActivity's onResume(), access the SharedPreference and then make your changes there. I do not like this method because you will be cluttering onResume() with more logic and you will also probably have to have a variable that keeps track of the state of the variable you are interested in.

我会亲自去与选项2,因为回调是为这一确切目的创建的。

这篇关于通过一个活动的引用到另一个活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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