【Androidアプリケーションの設定画面を作ろう】DialogPreferenceをカスタマイズする
DialogPreferenceを使って独自の設定項目を作成します。
今回はRatingBarをダイアログに表示してレーティングをプリファレンスに保存する設定項目を作成します。
| onCreateDialogView | ダイアログに表示するViewを設定します。 |
| onBindDialogView | ダイアログに表示するViewにプリファレンスからデータを設定します。 |
| onDialogClosed | ダイアログが消えるときに呼ばれるメソッドです。このメソッドでプリファレンスにデータを保存します。 |
public class MyRatingPreference extends DialogPreference {
private RatingBar rate;
public MyRatingPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MyRatingPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected View onCreateDialogView() {
FrameLayout frameLayout = new FrameLayout(getContext());
rate = new RatingBar(getContext());
rate.setNumStars(5);
rate.setProgress(1);
rate.setLayoutParams(new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT));
frameLayout.addView(rate);
return frameLayout;
}
@Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
float aFloat = getPersistedFloat(0);
rate.setRating(aFloat);
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if(positiveResult) {
persistFloat(rate.getRating());
}
}
}