我如何通过一个自定义类型的对象从一个活动到另一个使用类意图的putExtra()方法?


当前回答

迄今为止最简单的方法IMHO包裹对象。只需在希望可打包的对象上方添加注释标记。

下面是该库的一个示例https://github.com/johncarl81/parceler

@Parcel
public class Example {
    String name;
    int age;

    public Example(){ /*Required empty bean constructor*/ }

    public Example(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public String getName() { return name; }

    public int getAge() { return age; }
}

其他回答

快速需求的简短回答

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

你可以使用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");
}

在自定义类中声明并使用。

在臂膀上

在build.gradle中添加kotlin扩展。

apply plugin: 'kotlin-android-extensions'

android {
    androidExtensions {
        experimental = true
   }
}

然后像这样创建数据类。

@Parcelize
data class Sample(val id: Int, val name: String) : Parcelable

传递带有意图的对象

val sample = Sample(1,"naveen")

val intent = Intent(context, YourActivity::class.java)
    intent.putExtra("id", sample)
    startActivity(intent)

获取带有意图的对象

val sample = intent.getParcelableExtra("id")
Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);
startACtivity(i);

如果你对putExtra特性的使用不是很特别,只是想启动另一个带有对象的活动,你可以查看我写的GNLauncher (https://github.com/noxiouswinter/gnlib_android/wiki#gnlauncher)库,它试图使这个过程更直接。

GNLauncher可以将对象/数据从另一个活动发送到一个活动,就像调用活动中的函数一样简单,并将所需的数据作为参数。它引入了类型安全,并消除了必须序列化的所有麻烦,使用字符串键附加到意图,并在另一端撤销相同的操作。