かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

AlertDialogで背景のグレーになっている箇所をタップすると閉じるようにしたい

AlertDialog.Builderでダイアログを組み立てたあとにcreate()で取得したAlertDialogに対してsetCanceledOnTouchOutside(true)でいけるみたい。

package com.example.helloworld;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        MenuItem item1 = menu.findItem(R.id.item1);
        item1.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this);
                b.setTitle(R.string.app_name);
                b.setMessage(R.string.alert_message);
                b.setCancelable(true);
                b.setInverseBackgroundForced(true);
                
                AlertDialog d = b.create();
                // ここでセットするらしい
                d.setCanceledOnTouchOutside(true);
                d.show();
                return true;
            }
        });
        return true;
    }

}

ふむぅ。慣れないと難しいですな…Android。