我正在开发一个应用程序,它要求我在多个活动之间传递对象的引用并进行修改。这些修改需要在所有活动中反映对象。但是,我对Parcelable对象并不熟悉,而且我在实现这个问题时遇到了一些问题。
所以我有“Character Main”活动:
public class CharacterMainActivity extends AppCompatActivity {
private CharacterInfo myCharacter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_character_main);
Intent intent = getIntent();
myCharacter = (CharacterInfo) intent.getParcelableExtra("character");
setTitle(myCharacter.getCharacterName());
}
public void openCharacterSheet(View v) {
Intent intent = new Intent(this, CharacterSheetActivity.class);
intent.putExtra("character", myCharacter);
startActivity(intent);
}
}
然后在“角色表”活动中,它采用Parcelable并创建自己的引用,它通过使用几个字段进行修改:
public class CharacterSheetActivity extends AppCompatActivity {
private CharacterInfo myCharacter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_character_sheet);
Intent intent = getIntent();
myCharacter = (CharacterInfo) intent.getParcelableExtra("character");
if(myCharacter != null) {
{ // Set the character ability scores and modifiers.
EditText strInput = (EditText) findViewById(R.id.sheet_strength_input);
strInput.setText(String.valueOf(myCharacter.getAbilityScore(AbilityScore.Scores.STRENGTH)
.getScoreValue()));
strInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
if(!s.toString().isEmpty() && s.toString().matches("\\d+")) {
myCharacter.setAbilityScore(AbilityScore.Scores.STRENGTH,
Integer.parseInt(s.toString()));
TextView mod = (TextView) findViewById(R.id.sheet_str_mod_label);
mod.setText("Mod: " + myCharacter.getAbilityScore(AbilityScore.Scores.STRENGTH)
.getScoreModifier());
}
}
});
TextView modText = (TextView) findViewById(R.id.sheet_str_mod_label);
modText.setText("Mod: " + myCharacter.getAbilityScore(AbilityScore.Scores.STRENGTH)
.getScoreModifier());
} // End ability score set.
}
}
}
问题是,当我按BACK按钮返回上一个活动时(在Character Sheet的情况下,它返回Character Main),然后返回Character Sheet,我刚刚更改的值又回到了它以前是什么。
我在这里做错了什么?有没有办法实现这个目标?我知道使用对象的全局静态引用会更简单,但我想让它以正确的方式工作。有人能帮助我吗?