投稿

ラベル(ShredPref)が付いた投稿を表示しています

【Android】アノテーション @SharedPref を使う

Androidアプリケーションで設定などの値を保存する際に、アノテーションを利用して簡単に読み書きする方法をまとめてみます。 まずは通常の SharedPreferences クラスを利用する例が以下です。 SharedPreferencesクラスを使った例 // SharedPreferencesクラスを実体化 SharedPreferences preferences = getSharedPreferences("data", Context.MODE_PRIVATE); // IDを読み込み int id = preferences.getInt("id", 0); // IDを書き込み SharedPreferences.Editor editor = preferences.edit(); editor.putInt("id", 123); editor.apply(); これをアノテーション @SharedPref を使って書くと次のようになります。 @SharedPrefを使った例 // ※これはメンバー変数 @Pref static MyPreference_ preference; // IDを読み込み int id = preference.id().get(); // IDを書き込み preference.id().put(123); Editorを作ったり、keyを指定したりしなくていいのでだいぶすっきりします。 保存する設定値が多くなればなるほど、使いやすさが実感できると思います。 ただしこれを利用するにはもちろん前準備が必要になるので説明します。 前準備 ライブラリを追加 app/build.gradle dependencies { … } に以下の2行を追加します。 annotationProcessor "org.androidannotations:androidannotations:+" implementation "org.androidannotations:androidannotations-api:+" SharedPrefインターフェースを作成 以下のようなインタ