SharedPreference
値を保存および取得できる単なるファイルです。SharedPreference
アクティビティでaを使用する最も簡単な手順は次のとおりです。
使用するファイルをsP
指す変数を作成する必要があります。SharedPreferences
SharedPreferences sP = getSharedPreferences("MyPrefs", MODE_PRIVATE);
そのファイルの「エディタ」を指す変数を作成する必要がありますsPeD
。これにより、そのファイルに値を入れることができます。
SharedPreferences.Editor sPeD = sP.edit();
次に、そのファイルから保存された値を抽出できます。値は、定義した「キー」によってインデックスが付けられString
ます。
String myString = sP.getString("keyTextYouDefine", "Oops!");
"keyTextYouDefine"
キーに値が格納されていない場合はgetString()
、にmyString
等しくなり"Oops!"
ます。
そのキーの値を格納するには、次を使用します。
sPeD.putString("keyYouDefine","The string I want to save.");
sPeD.commit();
ファイルに物を入れた後でやることを忘れた場合commit()
、それらは実際にはそこに置かれません。
これでうまくいくはずです。
後で追加:
次に、これを使用して、ボタンにある画像を判別できます。
ボタンを適切に定義したと仮定します
Button button = findViewById(R.id.myButton) // or whatever you are actually using
次に、何かが保存されている場合は、何からでも画像を設定しますShardPreference
int which = sP.getInt("WhichImage", 1); // assuming image1 is the "default"
switch (which) {
case 1:
button.setCompoundDrawables(null, @drawable/image1, null, null);
break;
case 2:
button.setCompoundDrawables(null, @drawable/image2, null, null);
break;
default: // no image
}
アクティビティの他の場所で、ボタンの画像をimage2に切り替えることにした場合:
if (whatever) { // condition for changing to image 2
button.setCompoundDrawables(null, @drawable/image2, null, null);
sP.edit().putInt("WhichImage", 2).commit();
}
私はsetCompoundDrawables()
自分自身を使ったことがないので、あなたのマイレージは異なるかもしれません。