我如何使用一个变量从一个活动到另一个活动?



在我的MainActivity我有一个分数变量,int score = 0;

然而,我有另一个活动是DisplayScore活动(显示分数)txtFinalScore.setText("Score: " + score);

我如何使用相同的变量形式我的MainActivity到我的DisplayScore活动,以便我可以显示分数?

如果我没理解错的话,你应该这样做。

public class Main {
public static void main(String[] args) {
int score = 0; // the main activity thing
int displayScore = score; // the thing to use the same value as score
System.out.println("Score : " + displayScore); // to simulate the setText
}
}

这个问题完美地解释了如何为Intent使用putExtra()getExtra()方法,因为我认为这是你需要的。

另外,如果您觉得这很困难,您可以将分数值存储到sharedPreference中,并从另一个活动中检索它。你可以在这里看到文档。

最新更新