明らかな何かが欠けているのか、それともこれが実際にどうすればよいかわからないものなのかどうかはわかりませんが、いくつかの変数をリセットできるようにしたいと思います ( integers
)。それらをインクリメントするメソッドがあり、それらは に保存されSharedPreferences
ます。ボタンのクリックでこれらを 0 にリセットできるようにしたいと思います。
SharedPreferences
clear(); を使用してクリアできます。コマンドですが、intは同じままであるため、再度呼び出されるとすぐに、リセット前の状態に戻ります。また、それらを0に設定しようとしましたが、それ以上インクリメントできません。変数をリセットまたは削除する方法はありますか?
または、それが不可能/難しすぎる場合、これらの整数を完全にリセットできる別の方法はありますか?
ありがとう
これはインクリメント コードの一部です。これは機能します。私もクリアできSharedPreferences
ます。その部分もいいです。機能しない唯一の部分は、int を 0 にリセットすることですが、それを incrementable のままにします。
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();
}
}