虽然活动已关闭但保存价值

时间:2014-07-02 07:55:15

标签: android sharedpreferences

现在我想保存值(由于点击而改变),甚至关闭活动。

每当我点击按钮

时,分数会增加和减少

但我希望在关闭此活动后保存该值并重新打开它 有人说要用  SharedPreferences方法,但我不知道如何将其应用于我的方法。

请帮帮我

public class MouseActivity extends Activity implements OnClickListener{
    int score ;
    TextView Value,speed;
    ImageButton Plus, Minus;
    String msg = "10";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.mouseactivity);

        Plus = (ImageButton) findViewById(R.id.RClick);
        Minus = (ImageButton) findViewById(R.id.LClick);

        Value = (TextView) findViewById(R.id.number);
        speed = (TextView) findViewById(R.id.textView1);
        speed.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/beb.otf"));
        Plus.setOnClickListener((OnClickListener) this);
        Minus.setOnClickListener((OnClickListener) this);


        //왼 클릭 버튼 생성 및 이벤트 연결

       }
    @Override


public void onClick(View v)
{

    boolean showText = false;


if(v.getId()==R.id.RClick)
{


    if(score>=20)
    {score=20;

    String msg = "";
    Main.getInstance().sendMessage(msg);

    }
    else{
        score ++;
        String msg = "aa";
    Main.getInstance().sendMessage(msg);
    }
    }
else if (v.getId()==R.id.LClick)
{

            if(score<=0)
            {
            score=0;
            String msg = "";
            Main.getInstance().sendMessage(msg);
            }
            else{
                score --;
                String msg = "bb";
                Main.getInstance().sendMessage(msg);
            }
    }
else
{
    String msg = "";
    Main.getInstance().sendMessage(msg);

}

Value.setText(String.valueOf(score));

}

2 个答案:

答案 0 :(得分:0)

看看这里:http://developer.android.com/guide/topics/data/data-storage.html#pref

像这样保存:

  public static final String PREFS_NAME = "MyPrefsFile";

  ...

  SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
  SharedPreferences.Editor editor = settings.edit();
  editor.putInt("yourKey", yourValue);

像这样阅读

  SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
  int value = settings.getInt("yourKey", 0);

答案 1 :(得分:0)

将您的值保存在 onPause 活动方法上,并在 onStart onResume 方法上检索它。您可以这样做,因为在退出活动之前始终会调用onPause。 在onResume中获得分数的示例代码:

SharedPreferences preference = getSharedPreferences(
                "mypref", MODE_PRIVATE);
        String score= preference.getString(
                "score", "0");//score is 0 by default

要在onPause方法中保存条目:

SharedPreferences preference = getSharedPreferences(
                "mypref", MODE_PRIVATE);
SharedPreferences.Editor editor = preference.edit();
                editor.putString("score",
                        score+"");
                editor.commit();