我如何在Android的活动之间传递自定义对象?我知道有捆绑包(bundles)但是却无法在其中找到相关功能。是否能有人给我展示一个不错的例子?
你应该实现Parcelable接口。
链接到文档。
class Employee implements Parcelable
{
}
2) 将Parcelable对象传递到意图中,如下所示:
Employee mEmployee =new Employee();
Intent mIntent = new Intent(mContect,Abc.class);
mIntent.putExtra("employee", mEmployee);
startActivity(mIntent);
3) 将数据传递到新的 [Abc] Activity 中,如下所示:
Intent mIntent = getIntent();
Employee mEmployee = (Employee )mIntent.getParcelableExtra("employee");
Parcel
可能解决您的问题。
将Parcel
视为原始类型(long、String、Double、int等)的“数组”(比喻)。如果您的自定义类仅由原始类型组成,则更改类声明,包括implements Parcelable
。
您可以毫不费力地通过意图传递可包装对象(就像发送基本类型对象一样)。在这种情况下,我有一个名为FarmData的可包装自定义类(由长整型、字符串和双精度浮点数组成),我通过意图从一个活动传递到另一个活动。
FarmData farmData = new FarmData();
// code that populates farmData - etc etc etc
Intent intent00 = new Intent(getApplicationContext(), com.example.yourpackage.yourclass.class);
intent00.putExtra("farmData",farmData);
startActivity(intent00);
但是检索它可能会有些棘手。接收意图的活动将检查是否随意图一起发送了一组额外的数据。
Bundle extras = getIntent().getExtras();
FarmData farmData = new FarmData();
Intent intentIncoming = getIntent();
if(extras != null) {
farmData = (FarmData) intentIncoming.getParcelableExtra("farmData");// OK
}
假设有一个实现了整个对象树的可序列化 PasswordState 对象,你可以将该对象传递到另一个活动中:
private void launchManagePassword() {
Intent i= new Intent(this, ManagePassword.class); // no param constructor
PasswordState outState= new PasswordState(lengthKey,timeExpire,isValidKey,timeoutType,"",model.getIsHashPassword());
Bundle b= new Bundle();
b.putSerializable("jalcomputing.confusetext.PasswordState", outState);
i.putExtras(b);
startActivityForResult(i,REQUEST_MANAGE_PASSWORD); // used for callback
}
在活动之间传递对象或使对象对整个应用程序通用的一种简单方法是创建一个扩展Application的类。
以下是一个示例:
public class DadosComuns extends Application{
private String nomeUsuario="";
public String getNomeUsuario() {
return nomeUsuario;
}
public void setNomeUsuario(String str) {
nomeUsuario = str;
}
}
private DadosComuns dadosComuns;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//dados comuns
dadosComuns = ((DadosComuns)getApplicationContext());
dadosComuns.setNomeUsuario("userNameTest"); }
所有你实例化的其他活动,dadosComuns = ((DadosComuns)getApplicationContext()); 你可以访问 getNomeUsuario() == "userNameTest"
在你的AndroidManifest.xml中需要有
<application
android:name=".DadosComuns"