[Qiita] AppCompatのAlertDialogのテーマカラーを変える

※この記事は以前Qiitaに投稿されていた古い記事です

はじめに

Android Supoprt Library 22.1で公開されたandroid.support.v7.app.AlertDialogを使うと、Material Designなダイアログを簡単に実装することができますが、そのダイアログのタイトルの文字色やダイアログの背景色を変えるにはどうすれば良いのか、メモとして書いておきます。

style.xmlでカラーを定義

<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="colorAccent">@android:color/holo_blue_dark</item>
    <item name="android:background">@android:color/white</item>
    <item name="android:textColorPrimary">@android:color/holo_blue_light</item>
</style>
name どこの色
colorAccent ボタンの文字色とか
android:background ダイアログの背景色
android:textColorPrimary タイトル、メッセージの文字色

AlertDialog.BuilderでStyleをセットする

AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyAlertDialogStyle);
builder.setTitle("確認");
builder.setMessage("ほんとにいいの?");
builder.setPositiveButton("はい", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // ぽちっ
    }
});
builder.setNegativeButton("いいえ", null);
builder.create().show();

あとは実行するだけ

device-2015-11-16-223049.png

タイトル部分の背景だけ変えたいとき

int paddingLeftRight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics());
int paddingTopBottom = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, getResources().getDisplayMetrics());
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
// タイトル部分のTextView
TextView textView = new TextView(this);
// タイトルの背景色
textView.setBackgroundColor(ContextCompat.getColor(this, android.R.color.holo_blue_dark));
// タイトルの文字色
textView.setTextColor(Color.WHITE);
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setPadding(paddingLeftRight, paddingTopBottom, paddingLeftRight, paddingTopBottom);
// テキスト
textView.setText("確認");
// テキストサイズ
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
// タイトル部分にTextViewをセット
builder.setCustomTitle(textView);
// ここから下は一緒
builder.setMessage("ほんとにいいの?");
builder.setPositiveButton("はい", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // ぽちっ
    }
});
builder.setNegativeButton("いいえ", null);
builder.create().show();

あとは実行するだけ

device-2015-11-16-224103.png

まとめ

単純にダイアログの背景色やボタンの文字色だけを変更したいときはStyleで簡単に変更できました。
しかし、タイトル部分の背景だけを変えたい場合には、Styleでは変更できなかった(方法があるかもしれないけれどわからなかった)ので、少し手間がかかりましたが、なんとか実装できました。
もしStyleで変更する方法を知っている方がいましたら、教えていただけると嬉しいです。
以上、お疲れさまでした。



コメント

人気の投稿

[Qiita] Google Playのクローズドベータ版テストでメールアドレスを指定して公開する

[Qiita] Androidの実機でPCのlocalhostに接続したり、Webページの要素を検証する