我正在尝试使用从前一个活动中检索的getIntent值(得分),但似乎不可能。似乎在if下的加法和减法无法检测得分。还有其他办法吗?
package com.mkyong.android;
import com.mkyong.android.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
public class App2Activity extends Activity {
private RadioGroup radioAnswerGroup2;
private RadioButton radioAnswerButton2;
private Button btnSubmit2;
Button button2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
addListenerOnButton();
}
public void addListenerOnButton() {
final Context context = this;
radioAnswerGroup2 = (RadioGroup) findViewById(R.id.radioAnswer2);
button2 = (Button) findViewById(R.id.button2);
Button button2pre = (Button) findViewById(R.id.button2pre);
Intent intent = getIntent();
final int score = intent.getIntExtra("int", -1);
final TextView result2 = (TextView) findViewById(R.id.txtResult2);
result2.setText("Result counting: " + String.valueOf(score));
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int correctId2 = (R.id.answer2b);
// get selected radio button from radioGroup
int selectedId2 = radioAnswerGroup2.getCheckedRadioButtonId();
// find the radio button by returned id
radioAnswerButton2 = (RadioButton) findViewById(selectedId2);
if (selectedId2==correctId2){
score = score + 1;
//show toast saying it is correct
//Context context = getApplicationContext();
//CharSequence text = ("You are correct!");
//int duration = Toast.LENGTH_SHORT;
//Toast toast = Toast.makeText(context, text, duration);
//toast.show();
}
else{
score = score - 1;
//toast incorrect
//Context context = getApplicationContext();
//CharSequence text = ("You are wrong but it's ok and the answer is Data Link");
//int duration = Toast.LENGTH_LONG;
//Toast toast = Toast.makeText(context, text, duration);
//toast.show();
}
Intent intent2 = new Intent(App2Activity.this, App3Activity.class);
intent2.putExtra("int", score);
startActivity(intent2);
}
});
button2pre.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(context, AppActivity.class);
startActivity(intent);
}
});
}
}
答案 0 :(得分:9)
将int score
移动为全局变量,以便在onClick中访问它。您还需要删除final
关键字,以便在初始化后更改该值。
public class YourActivity extends Activity{
int score;
public onCreate( /*...etc.*/
答案 1 :(得分:1)
只需从以下位置删除final
关键字:
final int score = intent.getIntExtra("int", -1);
因为final
变量只能通过初始值设定项或赋值语句初始化一次。
了解更多here。