You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android(Java)如何将Pet类实例变量全局传递到其他Activity使用

实现自定义类实例全局传递的三种可行方案


方案1:自定义Application全局存储(最适合你的场景,解决实例创建晚于页面启动的问题)

该方案利用Android Application的全局生命周期特性,所有页面都可以随时读写存储的实例,实现最简单:

  1. 新建自定义Application类
public class MyApp extends Application {
    private Pet currentPet;
    private static MyApp instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public static MyApp getInstance() {
        return instance;
    }

    // 存储Pet实例
    public void setCurrentPet(Pet pet) {
        this.currentPet = pet;
    }

    // 获取Pet实例
    public Pet getCurrentPet() {
        return currentPet;
    }
}
  1. 在AndroidManifest.xml中注册自定义Application,找到<application>标签添加name属性:
<application
    android:name=".MyApp"
    <!-- 其他原有配置保持不变 -->
    >
    <!-- Activity等原有配置不变 -->
</application>
  1. 在AddPetScreen创建完Pet实例后存入全局存储:
// 原有创建pet1的代码后面添加
pet1 = new Pet(petNameTextVal, speciesChoice, petBDayTextVal, petNotesTextVal, "", 0, "");
MyApp.getInstance().setCurrentPet(pet1); // 存入全局
Toast.makeText(getApplicationContext(), "Success! " + pet1.getPetName() + " was added", Toast.LENGTH_SHORT).show();
finish(); // 关闭当前页面回到SelectPetScreen
  1. 在SelectPetScreen中重写onResume方法,每次页面回到前台时自动更新按钮文本(解决页面启动早于实例创建的问题):
@Override
protected void onResume() {
    super.onResume();
    Pet savedPet = MyApp.getInstance().getCurrentPet();
    if (savedPet != null) {
        pet1Button.setText(savedPet.getPetName());
    } else {
        pet1Button.setText("Placeholder name");
    }
}

方案2:实现Parcelable接口,通过Intent传递

适合不需要全局留存、仅页面间单次传递的场景:

  1. 给Pet类实现Parcelable接口:
public class Pet implements Parcelable {
    // 原有属性、方法保持不变

    protected Pet(Parcel in) {
        name = in.readString();
        species = in.readString();
        birthday = in.readInt();
        notes = in.readString();
        currentTime = in.readInt();
    }

    public static final Creator<Pet> CREATOR = new Creator<Pet>() {
        @Override
        public Pet createFromParcel(Parcel in) {
            return new Pet(in);
        }

        @Override
        public Pet[] newArray(int size) {
            return new Pet[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeString(species);
        dest.writeInt(birthday);
        dest.writeString(notes);
        dest.writeInt(currentTime);
    }
}
  1. 在SelectPetScreen中注册返回值监听:
private ActivityResultLauncher<Intent> addPetLauncher = registerForActivityResult(
    new ActivityResultContracts.StartActivityForResult(),
    result -> {
        if (result.getResultCode() == RESULT_OK && result.getData() != null) {
            Pet returnPet = result.getData().getParcelableExtra("pet_data");
            if (returnPet != null) {
                pet1Button.setText(returnPet.getPetName());
            }
        }
    }
);

// 修改跳转方法
public void openAddPetScreen() {
    Intent intent = new Intent(this, AddPetScreen.class);
    addPetLauncher.launch(intent);
}
  1. 在AddPetScreen创建完实例后回传数据:
pet1 = new Pet(petNameTextVal, speciesChoice, petBDayTextVal, petNotesTextVal, "", 0, "");
Intent resultIntent = new Intent();
resultIntent.putExtra("pet_data", pet1);
setResult(RESULT_OK, resultIntent);
finish();

方案3:持久化存储(适合需要App重启后仍保留数据的场景)

如果需要长期留存宠物信息,可以将Pet实例序列化后存入SharedPreferences、Room数据库等本地存储,任意页面随时读取即可。


内容的提问来源于stack exchange,提问作者Nicolas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 13:27:08