简体   繁体   English

Android活动之间的信息传递

[英]Information Passing between Android Activities

I have few activities that sets parameters for the last activity For eg Let's say I have 4 activities A->B->C->D. 我很少有活动为最后一个活动设置参数。例如,假设我有4个活动A-> B-> C-> D。 In A, B, C activities users selects few parameters that are finally needs to be available to D. Now there are two ways to achieve this 在A,B,C活动中,用户选择了一些最终需要D可用的参数。现在有两种方法可以实现此目的

  1. Pass the parameter values through activities using intent.putExtra Ie A passes its parameters to B and then B passes it to C and so on. 通过使用intent.putExtra的活动将参数值传递给活动。A将其参数传递给B,然后B将其传递给C,依此类推。
  2. Store these in some static class, Activity D can access it from there. 将它们存储在某个静态类中,Activity D可以从那里访问它。

Just want to know, which of these approaches is best and why? 只想知道,哪种方法最好,为什么?

That really depends on your needs and how much information. 这实际上取决于您的需求以及多少信息。 If there is very little information (maybe 2 or 3 pieces of data) I would say using putExtra() is fine and maybe suggest putting them in a Bundle so you don't have to worry about each extra every Activity . 如果信息很少(可能是2或3个数据),我会说使用putExtra()很好,并建议将它们放在Bundle这样您就不必担心每一个Activity都会增加额外的putExtra()

If you are dealing with much more than that then I would suggest adding them to a separate class. 如果您要处理的远远不止这些,那么我建议您将它们添加到单独的类中。 IMO, it will be much easier to maintain this way, less chances for syntax errors (such as misspelling a "key" parameter) and more flexible if you decide to use the data in other ways. IMO,这样维护起来会容易得多,语法错误(例如拼写错误的“ key”参数)的机会更少,如果您决定以其他方式使用数据,则更加灵活。

In my current app, it started out using extras , just a few, then grew into many more. 在我当前的应用程序中,它最初仅使用extras ,然后使用了更多。 It got unmanageable as the data ended up being passed around and used in so many different classes. 由于数据最终被传递并用于许多不同的类中,因此它变得难以管理。 I just finished up creating a couple separate classes using static HashMaps, ArrayLists, and ContenValues , among other objects . 我刚完成使用static HashMaps, ArrayLists, and ContenValuesobjects创建了几个单独的类。 I then had to migrate all of the extras data to these classes. 然后,我不得不将所有extras数据迁移到这些类。

Android开发人员网站对跨活动数据传递选项以及建议的使用时间进行了全面的回顾,最好是对它们进行回顾并选择最适合您情况的解决方案。

There is also a 3rd method to store your parameters in Shared Preferences 还有第三种方法可以将参数存储在“ 共享首选项”中

here is the tutorial , ie how to implement shared prefrences. 这是本教程 ,即如何实现共享首选项。

If you are using the shared pref in your code then there is no any need of passing your data(parameters) from Activity A->B->C and to D in. you just have to save your data (parameter) once and can regain back on any activity. 如果在代码中使用共享首选项,则无需将数据(参数)从活动A-> B-> C传递到D in。您只需保存一次数据(参数)即可重新获得任何活动。

Hope this helps 希望这可以帮助

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

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