読者です 読者をやめる 読者になる 読者になる

redev

technical miscellaneous memorandum

Preference画面からNumberPickerダイアログを作成する

Android

preference.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory android:title="category">
        <Preference
            android:key="key"
            android:title="title" />
    </PreferenceCategory>
</PreferenceScreen>


dialog_hoge.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <NumberPicker
        android:id="@+id/number1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


呼び出し側でクリック時のリスナーを設定する

    Preference pref = findPreference("key");
    pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            class ExDialog extends DialogFragment {
                @Override
                public Dialog onCreateDialog(Bundle savedInstanceState) {
                    LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    View view = inflater.inflate(R.layout.dialog_hoge, null);
                    NumberPicker numberPicker = (NumberPicker)view.findViewById(R.id.number1);
                    numberPicker.setMaxValue(10);
                    numberPicker.setValue(1);

                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setTitle("title"));
                    builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // OKクリック時の処理
                        }
                    });
                    builder.setNegativeButton("cancel", null);
                    builder.setView(view);
                    return builder.create();

                }

            }
            ExDialog dialog = new ExDialog();
            dialog.show(getFragmentManager(), "");
            return false;
        }
    });