/*我已经声明了一个全局变量plusMarks,并在checkAnswer((方法中使用了这个变量,并调用了这个方法。*/
private int plusMarks=0;
// private int minusMarks=0;
// private int TotalScore;
@SuppressLint("SetTextI18n")
private void checkAnswer(boolean userPressed) {
boolean answerProvided = mQuestionBank[mCurrentIndex].isQuestionTrueAnswer();
//int messageStringId = 0;
if (answerProvided == userPressed) {
// messageStringId = R.string.correct_toast;
mGreenTick.setImageResource(R.drawable.green_tick);
mGreenTick.setVisibility(View.VISIBLE);
plusMarks++;
}
else {
// messageStringId = R.string.incorrect_toast;
mGreenTick.setImageResource(R.drawable.red_cross);
mGreenTick.setVisibility(View.VISIBLE);
// minusMarks++;
}
// TotalScore = plusMarks - minusMarks;
mScoreTextview.setText("Your Score is = " + plusMarks + " Marks out of 10 Marks");
// Toast.makeText(MainActivity.this, messageStringId, Toast.LENGTH_SHORT).show();
}
/*我在两个按钮中调用了checkAnswer((方法我已经创建了一个新的活动ScoreActivity,我想在新的活动文本视图中转换变量plusMarks的值。但不幸的是,经过多次尝试,我无法做到这一点,它在我的文本视图中显示了null值。请帮助我并给出解决方案*/
mScoreButton = (Button)findViewById(R.id.score_button);
mScoreButton.setVisibility(View.INVISIBLE);
mScoreButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
**Intent intent = new Intent(MainActivity.this, ScoreActivity.class);
startActivity(intent);
intent.putExtra("PLUS_MARKS", plusMarks);
finish();**
}
});
This is the new activity i have created
public class ScoreActivity extends AppCompatActivity {
private TextView mFinalMarks;
private Button mExitApp;
private Intent PLUS_MARKS;
@SuppressLint("SetTextI18n")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
mFinalMarks = (TextView)findViewById(R.id.final_marks);
// mFinalMarks.setText("Final Score is: " + getIntent().getStringExtra("PLUS_MARKS") + "Marks
10〃中的10〃(;
// mFinalMarks.setText(getIntent().getStringExtra("PLUS_MARKS"));
**mFinalMarks.setText("Final Score is: " + getIntent().getStringExtra("PLUS_MARKS"));**
/*我想在新的活动文本视图mFinalMarks中传输全局变量plusMarks的值。我试了很多次,但它显示为空值。请帮帮我。它还要求编辑代码以更好地理解。*/
您必须将;额外的";在之前的Intent
中调用startActivity()
。您有:
startActivity(intent);
intent.putExtra("PLUS_MARKS", plusMarks);
你需要这样做:
intent.putExtra("PLUS_MARKS", plusMarks);
startActivity(intent);
注意:此外,您没有";全局变量";。plusMarks
是一个类的私有成员变量。A";全局变量";Java中会声明为public static
,这样任何类都可以直接访问它。
现代方式是使用-ActivityResultApi