Skip to content

Instantly share code, notes, and snippets.

@wheeliechamp
Created April 30, 2020 12:54
Show Gist options
  • Save wheeliechamp/952d4249b5f876771631219b7be59a2e to your computer and use it in GitHub Desktop.
Save wheeliechamp/952d4249b5f876771631219b7be59a2e to your computer and use it in GitHub Desktop.
Activity以外から更新とSharedPreferencesの使い方
import android.content.Context;
import android.content.SharedPreferences;
import android.widget.TextView;
import static android.content.Context.MODE_PRIVATE;
public class TextChange {
private Context appContext;
public TextChange(Context context) {
appContext = context;
}
public void textChange() {
TextView textView1 = (TextView)((MainActivity)appContext).findViewById(R.id.textView1);
textView1.setText("アイウエオ");
SharedPreferences pref = appContext.getSharedPreferences("data", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("data_1", "DATA_1");
editor.putString("data_2", "DATA_2");
editor.apply();
TextView textView2 = (TextView)((MainActivity)appContext).findViewById(R.id.textView2);
textView2.setText(pref.getString("data_2", "---"));
MainActivity.testTest();
TestClass test_class = new TestClass();
test_class.SampleTest();
}
// サブクラス
private class TestClass {
public void SampleTest() {
System.out.println("Hello!!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment