我尝试在单击保存按钮时从我的篮球比赛计数器应用程序存储比赛分数,包括球队名称和日期。
Java代码如下:
package com.example.android.courtcounter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
int scoreTeamA = 0;
int scoreTeamB = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayForTeamA(0);
displayForTeamB(0);
setTitle("Basketball Count");
Toast.makeText(getApplicationContext(), "You can change team names and scores manually by clicking on them", Toast.LENGTH_LONG).show();
}
// +3 Points for Team A
public void addThreeForTeamA (View view) {
scoreTeamA = scoreTeamA + 3;
displayForTeamA(scoreTeamA);
}
// +2 Points for Team A
public void addTwoForTeamA (View view) {
scoreTeamA = scoreTeamA + 2;
displayForTeamA(scoreTeamA);
}
// +1 Point for Team A
public void addOneForTeamA (View view) {
scoreTeamA = scoreTeamA +1;
displayForTeamA(scoreTeamA);
}
// Displays the given score for Team A.
public void displayForTeamA(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_a_score);
scoreView.setText(String.valueOf(score));
}
// +3 Points for Team B
public void addThreeForTeamB (View view) {
scoreTeamB = scoreTeamB + 3;
displayForTeamB(scoreTeamB);
}
// +2 Points for Team B
public void addTwoForTeamB (View view) {
scoreTeamB = scoreTeamB + 2;
displayForTeamB(scoreTeamB);
}
// +1 Point for Team B
public void addOneForTeamB (View view) {
scoreTeamB = scoreTeamB +1;
displayForTeamB(scoreTeamB);
}
// Displays the given score for Team B.
public void displayForTeamB(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_b_score);
scoreView.setText(String.valueOf(score));
}
public void resetScore (View view) {
scoreTeamA = 0;
scoreTeamB = 0;
displayForTeamA(scoreTeamA);
displayForTeamB(scoreTeamB);
}
}
我已将分数和球队名称存储在 EditText View 中,并希望保存它们并在以后加载它们。有人知道用什么来保存和加载特定的游戏分数吗?
最佳答案
我从 Udacity 的优秀“Android 入门”类(class)中识别出这段代码。您必须使用 sharedPreferences
来保存分数。例如:
SharedPreferences sharedPref = getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("scoreTeamA", scoreTeamA);
editor.putInt("scoreTeamB", scoreTeamB);
editor.apply();
然后检索值:
SharedPreferences sharedPref = getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
int scoreTeamA = sharedPref.getInt(scoreTeamA, 0);
int scoreTeamB = sharedPref.getInt(scoreTeamB, 0);
关于java - 我如何为篮球比分计数器应用程序存储包括球队名称在内的比赛比分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39192792/