繁体   English   中英

在活动之间传递自定义对象?

[英]Passing custom objects between activities?

如何在android中的活动之间传递自定义对象? 我知道捆绑包,但我似乎看不到其中的任何功能。 谁能告诉我一个很好的例子?

您应该实现Parcelable 接口

链接到文档

使用 Parcelable 接口,您可以将自定义 java 对象传递到意图中。

1) 为您的类实现 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

您可以毫无困难地通过 Intent 传递 Parcelable 对象(就像发送原始类型对象一样)。 在这种情况下,我有一个名为FarmData的可打包自定义类(由 longs、strings 和 doubles 组成),我通过意图从一个活动传递到另一个活动。

    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);    

但检索它可能很棘手。 接收到 Intent 的 Activity 将检查是否与 Intent 一起发送了一个额外的包。

    Bundle extras = getIntent().getExtras();
    FarmData farmData = new FarmData();
    Intent intentIncoming = getIntent();
    if(extras != null) {
        farmData = (FarmData) intentIncoming.getParcelableExtra("farmData");// OK
    }

给定一个在整个对象树中实现 Serializable 的对象 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
}

在活动之间传递对象或使对象对所有应用程序通用的一种简单方法是创建一个扩展应用程序的类。

下面是一个例子:

public class DadosComuns extends Application{

    private String nomeUsuario="";

    public String getNomeUsuario() {
        return nomeUsuario;
    }

    public void setNomeUsuario(String str) {
        nomeUsuario = str;
    }
}

在所有其他活动中,您只需要实例化一个对象“DadosComuns”,声明为全局变量。

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"

暂无
暂无

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

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