我如何通过一个自定义类型的对象从一个活动到另一个使用类意图的putExtra()方法?
当前回答
我也遇到过同样的问题。我通过使用一个静态类来解决这个问题,在HashMap中存储我想要的任何数据。在上面,我使用了标准活动类的扩展,其中我覆盖了onCreate和onDestroy方法来做数据传输和数据清除隐藏。一些荒谬的设置必须改变,例如方向处理。
注释: 不提供一般对象传递给另一个活动是痛苦的屁股。这就像射击自己的膝盖,希望赢得100米。“比喻”并不是一个充分的替代品。这让我笑了……我不想实现这个接口到我的技术自由API,因为我更不想引入一个新的层…这是怎么回事,我们在移动编程中离现代范式如此之远……
其他回答
你可以使用putExtra(Serializable..)和getSerializableExtra()方法来传递和检索你的类类型的对象;你必须将你的类标记为Serializable,并确保你所有的成员变量也是Serializable…
对于你知道要在应用程序中传递数据的情况,使用“全局变量”(比如静态类)
以下是Dianne Hackborn (hackbod -谷歌安卓软件工程师)对此事的看法:
For situations where you know the activities are running in the same process, you can just share data through globals. For example, you could have a global HashMap<String, WeakReference<MyInterpreterState>> and when you make a new MyInterpreterState come up with a unique name for it and put it in the hash map; to send that state to another activity, simply put the unique name into the hash map and when the second activity is started it can retrieve the MyInterpreterState from the hash map with the name it receives.
快速需求的简短回答
1. 将类实现为可序列化的。
如果你有任何内部类,不要忘记将它们实现为Serializable !!
public class SportsData implements Serializable
public class Sport implements Serializable
List<Sport> clickedObj;
2. 将你的对象放入Intent中
Intent intent = new Intent(SportsAct.this, SportSubAct.class);
intent.putExtra("sport", clickedObj);
startActivity(intent);
3.并在另一个活动类中接收您的对象
Intent intent = getIntent();
Sport cust = (Sport) intent.getSerializableExtra("sport");
我发现最简单的解决办法是… 创建带有getter和setter的静态数据成员的类。
从一个活动中设置并从另一个活动中获取该对象。
活动
mytestclass.staticfunctionSet("","",""..etc.);
活动b
mytestclass obj= mytestclass.staticfunctionGet();
你可以使用android BUNDLE来做到这一点。
从你的类中创建一个Bundle,像这样:
public Bundle toBundle() {
Bundle b = new Bundle();
b.putString("SomeKey", "SomeValue");
return b;
}
然后用INTENT传递这个bundle。 现在你可以通过传递bundle来重新创建你的类对象
public CustomClass(Context _context, Bundle b) {
context = _context;
classMember = b.getString("SomeKey");
}
在自定义类中声明并使用。
推荐文章
- 改变开关的“开”色
- 以编程方式将EditText的输入类型从PASSWORD更改为NORMAL,反之亦然
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- 如何设置整个应用程序在纵向模式?
- Android中文本的阴影效果?
- 以编程方式设置TextView的布局权重
- Android -如何覆盖“后退”按钮,所以它不完成()我的活动?
- 如何从通知点击发送参数到一个活动?
- 导航目标xxx对于这个NavController是未知的
- 使用ConstraintLayout均匀间距的视图
- 文件google-services错误。模块根文件夹中缺少Json。谷歌服务插件没有它就不能正常工作。