我做了quiz
,在測驗我有3個活動Question1
,Question2
,Question3
,並在每個有4個可能的答案(按鈕),只有一個按鈕是正確的。我必須在測驗結束時計算並顯示用戶的分數。計算分數在Android
我已經做了一些研究,SHAREDPREFERENECES
似乎是解決方案。但我不知道如何使用它可以請任何人幫助。 Question1.java
代碼如下:假設btnAnswer1a
是正確的答案,我如何保存數據,然後在上一個活動中將其顯示在textview
中。
Button Answer1, Answer2, Answer3, Answer4;
public static final String PREFS_NAME = "MyPrefsFile";
static SharedPreferences settings;
SharedPreferences.Editor editor;
int ScoreCount;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.answer1);
settings = getSharedPreferences(PREFS_NAME, 0);
editor = settings.edit();
ScoreCount = settings.getInt("ScoreCount", 10);
Answer1 = (Button) findViewById(R.id.btnAnswer1a);
Answer2 = (Button) findViewById(R.id.btnAnswer1b);
Answer3 = (Button) findViewById(R.id.btnAnswer1c);
Answer4 = (Button) findViewById(R.id.btnAnswer1d);
Answer1.setOnClickListener(this);
Answer2.setOnClickListener(this);
Answer3.setOnClickListener(this);
Answer4.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.btnAnswer1a:
Intent Screen1 = new Intent(Answer1.this, Color2.class);
Answer1.this.startActivity(Screen1);
editor.putInt("ScoreCount", 6);
editor.commit();
break;
case R.id.btnAnswer1b:
Intent Screen = new Intent(Answer1.this, Color2.class);
Answer1.this.startActivity(Screen);
break;
case R.id.btnAnswer1c:
Intent Screen3 = new Intent(Answer1.this, Color2.class);
Answer1.this.startActivity(Screen3);
break;
case R.id.btnAnswer1d:
Intent Screen2 = new Intent(Answer1.this, Color2.class);
Answer1.this.startActivity(Screen2);
break;
}
當用戶回答您的測驗問題時,您將值寫入sharedPreferences(代碼的第一部分)。 S在你的情況下在每一個活動。當你想顯示結果時,你從sharedPreferences獲得值,所以我想在最後的活動。 – Agata