我如何通过一个自定义类型的对象从一个活动到另一个使用类意图的putExtra()方法?
当前回答
如果你对putExtra特性的使用不是很特别,只是想启动另一个带有对象的活动,你可以查看我写的GNLauncher (https://github.com/noxiouswinter/gnlib_android/wiki#gnlauncher)库,它试图使这个过程更直接。
GNLauncher可以将对象/数据从另一个活动发送到一个活动,就像调用活动中的函数一样简单,并将所需的数据作为参数。它引入了类型安全,并消除了必须序列化的所有麻烦,使用字符串键附加到意图,并在另一端撤销相同的操作。
其他回答
您需要将对象序列化为某种字符串表示形式。一种可能的字符串表示是JSON,如果你问我,在android中序列化JSON最简单的方法之一是通过谷歌GSON。
在这种情况下,你只需要输入字符串返回值from (new Gson()).toJson(myObject);并检索字符串值并使用fromJson将其转换回您的对象。
但是,如果您的对象不是非常复杂,那么可能不值得这样做,您可以考虑传递对象的单独值。
我也遇到过同样的问题。我通过使用一个静态类来解决这个问题,在HashMap中存储我想要的任何数据。在上面,我使用了标准活动类的扩展,其中我覆盖了onCreate和onDestroy方法来做数据传输和数据清除隐藏。一些荒谬的设置必须改变,例如方向处理。
注释: 不提供一般对象传递给另一个活动是痛苦的屁股。这就像射击自己的膝盖,希望赢得100米。“比喻”并不是一个充分的替代品。这让我笑了……我不想实现这个接口到我的技术自由API,因为我更不想引入一个新的层…这是怎么回事,我们在移动编程中离现代范式如此之远……
创建Android应用程序
文件>>新建>> Android应用程序
输入项目名称:android-pass-object-to-activity
Pakcage: com.hmkcode.android
保持其他默认选择,点击下一步直到完成
在开始创建应用程序之前,我们需要创建POJO类“Person”,我们将使用它将对象从一个活动发送到另一个活动。注意,该类正在实现Serializable接口。
将位于
package com.hmkcode.android;
import java.io.Serializable;
public class Person implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private int age;
// getters & setters....
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
两个活动的两种布局
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/tvName"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:text="Name" />
<EditText
android:id="@+id/etName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/tvAge"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:text="Age" />
<EditText
android:id="@+id/etAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</LinearLayout>
<Button
android:id="@+id/btnPassObject"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Pass Object to Another Activity" />
</LinearLayout>
activity_another.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="@+id/tvPerson"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_gravity="center"
android:gravity="center_horizontal"
/>
</LinearLayout>
两个活动类别
1)ActivityMain.java
package com.hmkcode.android;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
Button btnPassObject;
EditText etName, etAge;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPassObject = (Button) findViewById(R.id.btnPassObject);
etName = (EditText) findViewById(R.id.etName);
etAge = (EditText) findViewById(R.id.etAge);
btnPassObject.setOnClickListener(this);
}
@Override
public void onClick(View view) {
// 1. create an intent pass class name or intnet action name
Intent intent = new Intent("com.hmkcode.android.ANOTHER_ACTIVITY");
// 2. create person object
Person person = new Person();
person.setName(etName.getText().toString());
person.setAge(Integer.parseInt(etAge.getText().toString()));
// 3. put person in intent data
intent.putExtra("person", person);
// 4. start the activity
startActivity(intent);
}
}
2)AnotherActivity.java
package com.hmkcode.android;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class AnotherActivity extends Activity {
TextView tvPerson;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
// 1. get passed intent
Intent intent = getIntent();
// 2. get person object from intent
Person person = (Person) intent.getSerializableExtra("person");
// 3. get reference to person textView
tvPerson = (TextView) findViewById(R.id.tvPerson);
// 4. display name & age on textView
tvPerson.setText(person.toString());
}
}
你可以通过intent发送可序列化对象
// send where details is object
ClassName details = new ClassName();
Intent i = new Intent(context, EditActivity.class);
i.putExtra("Editing", details);
startActivity(i);
//receive
ClassName model = (ClassName) getIntent().getSerializableExtra("Editing");
And
Class ClassName implements Serializable {
}
如果你只是传递对象,那么Parcelable就是为这个设计的。使用它需要比使用Java的本机序列化多一点努力,但它要快得多(我的意思是快得多)。
从文档中,一个简单的例子是如何实现的:
// simple class that just has one member property as an example
public class MyParcelable implements Parcelable {
private int mData;
/* everything below here is for implementing Parcelable */
// 99.9% of the time you can just ignore this
@Override
public int describeContents() {
return 0;
}
// write your object's data to the passed-in Parcel
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
// example constructor that takes a Parcel and gives you an object populated with it's values
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
请注意,如果要从给定的Parcel中检索多个字段,则必须按照放入它们的相同顺序(即采用FIFO方法)执行此操作。
一旦你有你的对象实现Parcelable,这只是一个问题,把他们放入你的意图与putExtra():
Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);
然后你可以用getParcelableExtra()把它们拉回来:
Intent i = getIntent();
MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra");
如果你的对象类实现了Parcelable和Serializable,那么请确保转换为以下类型之一:
i.putExtra("parcelable_extra", (Parcelable) myParcelableObject);
i.putExtra("serializable_extra", (Serializable) myParcelableObject);
推荐文章
- 改变开关的“开”色
- 以编程方式将EditText的输入类型从PASSWORD更改为NORMAL,反之亦然
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- 如何设置整个应用程序在纵向模式?
- Android中文本的阴影效果?
- 以编程方式设置TextView的布局权重
- Android -如何覆盖“后退”按钮,所以它不完成()我的活动?
- 如何从通知点击发送参数到一个活动?
- 导航目标xxx对于这个NavController是未知的
- 使用ConstraintLayout均匀间距的视图
- 文件google-services错误。模块根文件夹中缺少Json。谷歌服务插件没有它就不能正常工作。