如何保存int数据,然后编辑按钮的onclick数字?

问题描述:

我想要这样做,所以当你点击回答者之一(Q1A1或Q1A2)时,它会给testScore int添加一些点数,所以我可以稍后在后面的课程中调用它,这样他们得到的分数将会是张贴在那里。感谢任何人提前帮助!
这里是我的代码,如何保存int数据,然后编辑按钮的onclick数字?

import android.app.Activity; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.TextView; 

public class Test extends Activity implements OnClickListener 

{ 

    TextView Q1A1; 
    TextView Q1A2; 
    TextView test; 

    public static final String PREFS_NAME = "MyPrefsFile"; 
    public static final int testScore = 0; 

    @Override 
public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.test); 
     Q1A1 = (TextView) findViewById(R.id.Q1A1); 
     Q1A2 = (TextView) findViewById(R.id.Q1A2); 
     Q1A1.setOnClickListener(this); 
     Q1A2.setOnClickListener(this); 
     test = (TextView) findViewById(R.id.test); 




     SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 
     test.setText(settings.getString("YourScore", "No Score")); 


    } 

    public void onClick(View v) 
    { 
     switch(v.getId()) 
     { 
     case R.id.Q1A1: 

      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 
      SharedPreferences.Editor editor = settings.edit(); 
      editor.putInt("YourScore", (testScore + 10)); 
      editor.commit(); 

      //Intent FinalScore = new Intent(this, FinalScore.class); 
      //startActivity(FinalScore); 
      break; 
     case R.id.Q1A2: 

      break; 
     } 
    } 
} 

感谢您正在保存你的分数为int,但称它作为一个字符串的帮助

+0

哪里,具体来说,你有问题?这段代码在第一次看起来似乎没问题。 – 2012-02-03 23:42:40

变化

test.setText(settings.getString( “YourScore”, “无得分”));

test.setText( “” + settings.getInt( “YourScore”,0));

+0

第二件事是testScore总是从零开始。您可能想将其设置为您保存的分数。 testScore = settings.getInt(“YourScore”,0); – 2012-02-04 00:02:22

+0

感谢它的工作,但现在如果我想要第二个按钮添加一个不同数量的分数,但仍然保存,如果这是有道理的。 所以如果我有第二个按钮Q1A2 whith所有相同的代码,但+ 5而不是10我得到第二个“设置”和“编辑器”的错误说改变名称,但他们不会设置的文本不工作? – 2012-02-06 01:40:12

+0

老实说,我不确定你这次问什么。如果你可以将这个答案标记为很好解决。如果您无法解决您的新问题,请尝试使用更新后的代码将其发布到新问题中。如果我看到它,我会尽力为你解决。 – 2012-02-06 12:17:38