我不确定我是否遗漏了一些明显的东西,或者这是否真的是我不知道该怎么做的事情,但我希望能够重置一些变量(integers
)。我有一个增加它们的方法,它们保存在SharedPreferences
. 我希望能够在单击按钮时将这些重置为 0。
我可以SharedPreferences
使用 clear(); 命令,但整数保持不变,因此一旦再次调用它们,它们就会恢复到重置前的状态。我也尝试将它们设置为 0,但是我不能再增加它们了。有没有办法只重置或删除变量?
或者,如果这不可能/太难,有没有另一种方法可以完全重置这些整数?
谢谢
这是递增代码的一部分。这行得通。我也可以清除SharedPreferences
;那部分也很好。唯一不起作用的部分是将 int 重置为 0,但保持它可递增。
Button PlusOneButton = ((Button)findViewById(R.id.plusonebutton));
PlusOneButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
intName++;
}});
编辑:有效的最终代码
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ThirdScreenActivity extends Activity {
public int myIntPlusOne;
public static final String PREFS = "MyPrefsFile";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);
SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences("PREFS", 0);
myIntPlusOne = sharedPrefs.getInt("myIntPlusOneSaved", 0);
if ("ListView Item 1".equals(position)) {
myIntPlusOne = sharedPrefs.getInt("myIntPlusOneSaved", 0);
TextView PlusOne = ((TextView)findViewById(R.id.plusonetextview));
PlusOne.setText(String.valueOf(myIntPlusOne));
Button PlusOneButton = ((Button)findViewById(R.id.plusonebutton));
PlusOneButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
myIntPlusOne++;
TextView PlusOne = ((TextView)findViewById(R.id.plusonetextview));
PlusOne.setText((myIntPlusOne)+"");
SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences("PREFS", 0);
Editor editor = sharedPrefs.edit();
editor.putInt("myIntPlusOneSaved", myIntPlusOne);
editor.commit();
}
});
}
else if...
}
Button btnClear = (Button) findViewById(R.id.clearbtn);
btnClear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myIntPlusOne=0;
TextView PlusOne = ((TextView)findViewById(R.id.plusonetextview));
PlusOne.setText("0");
}
});
}
public void onPause() {
super.onPause();
SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences("PREFS", 0);
Editor editor = sharedPrefs.edit();
editor.putInt("myIntPlusOneSaved", myIntPlusOne);
editor.commit();
}
}