如何在捆绑包中传递自定义对象?

2022-08-31 21:28:46

我正在尝试将我自己的自定义对象传递到捆绑包中:

Bundle b = new Bundle();
                STMessage message = (STMessage)a.getAdapter().getItem(position);
                b.putObject("message",message);

我收到错误:

The method putObject(String, Object) is undefined for the type Bundle

答案 1

一种方法是让您的自定义对象实现可 Parcelable 接口并使用Bundle.putParcelable/Bundle.getParcelable


答案 2

模型类

package com.sam.bundleobjectpass;

import java.io.Serializable;

/**
 * Created by Samir on 31.8.2016.
 */
public class Model implements Serializable {
    private String name;
    private String surName;
    private int age;

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

    public String getName() {
        return name;
    }

    
    public String getSurName() {
        return surName;
    }


    public int getAge() {
        return age;
    }


}

主要活动

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Model model = new Model("Sam", "Sami",32);
        
        Intent i = new Intent(MainActivity.this, ReceiverActivity.class);
        i.putExtra("Editing", model); // sending our object. In Kotlin is the same
        startActivity(i);

    }
}

接收器活动

public class ReceiverActivity extends Activity {

    TextView txt_name;
    TextView txt_surname;
    TextView txt_age;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);

        txt_name = (TextView)findViewById(R.id.txt_name);
        txt_surname = (TextView)findViewById(R.id.txt_surname);
        txt_age = (TextView)findViewById(R.id.txt_age);
        // receiving our object
        Model model = (Model) getIntent().getSerializableExtra("Editing");

        txt_name.setText(model.getName());
        txt_surname.setText(model.getSurName());
        txt_age.setText(""+model.getAge());


    }
}

科特林

val model: ProgramModel? = intent.getSerializableExtra("Editing") as ProgramModel?
        model?.let { // means if not null or empty
            txt_act_daily_topic.text = it.title
        }