2013年9月29日日曜日

androidカスタムダイアログの作り方

androidでカスタムダイアログを作った例です。

○ソースコード




        LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
        final View viewSettingDialog = inflater.inflate(R.layout.setting_dialog, (ViewGroup)findViewById(R.id.layout_root));
        ((CheckBox)viewSettingDialog.findViewById(R.id.checkBoxVibrator)).setChecked(true);
        ((SeekBar)viewSettingDialog.findViewById(R.id.seekBarVolume)).setProgress(50);
        
        //
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(viewSettingDialog);
        builder.setPositiveButton("OK", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) { // OKボタンクリック処理
                boolean valVib = ((CheckBox)viewSettingDialog.findViewById(R.id.checkBoxVibrator)).isChecked();
                int valVol = ((SeekBar)viewSettingDialog.findViewById(R.id.seekBarVolume)).getProgress();
            }
        });
        builder.setNegativeButton("Cancel", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // Cancel ボタンクリック処理
            }
        });
        builder.create().show();



○setting_dialog.xml
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/layout_root"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="10dp" >
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/option_volume" />
        <SeekBar
            android:id="@+id/seekBarVolume"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:max="100"
            android:padding="16dp"
            android:progress="50" />
        <CheckBox
            android:id="@+id/checkBoxVibrator"
            android:layout_width="308dp"
            android:layout_height="wrap_content"
            android:text="@string/option_vibrator" />
    </LinearLayout>




画面はeclipseでデザインできるので便利です。
その際に「LinearLayout」にID「layout_root」を付けておき、
その「layout_root」を「R.id.layout_root」と
もう一つ、「R.layout.setting_dialog」でinflateでViewで読み込んで表示します。

eclipseでデザインできるのが便利ですねえ。



0 件のコメント:

コメントを投稿