为AlertDialog按钮图片 [英] Images for AlertDialog buttons

查看:187
本文介绍了为AlertDialog按钮图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能可绘制添加到的中性的一个AlertDialog的按钮?如果是,那么如何?

Is it possible to add drawables to the positive, negative and neutral buttons of an AlertDialog? If yes, then how?

推荐答案

由于在prepareDialog 是德precated,您可以使用 onShowListener 代替。

Since onPrepareDialog is deprecated, you can use the onShowListener instead.

你也应该设置可绘制边界,否则将被放在最左边。

Also you should set the Drawable bounds or it will be placed far left.

的code以下

public class MyDialog extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setTitle("My Dialog")
                .setNegativeButton("Cancel", new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                    }
                }).setPositiveButton("Play", new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                    }
                }).create();
        dialog.setOnShowListener(new OnShowListener() {

            @Override
            public void onShow(DialogInterface dialogInterface) {
                Button button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);

                // if you do the following it will be left aligned, doesn't look
                // correct
                // button.setCompoundDrawablesWithIntrinsicBounds(android.R.drawable.ic_media_play,
                // 0, 0, 0);

                Drawable drawable = getActivity().getResources().getDrawable(
                        android.R.drawable.ic_media_play);

                // set the bounds to place the drawable a bit right
                drawable.setBounds((int) (drawable.getIntrinsicWidth() * 0.5),
                        0, (int) (drawable.getIntrinsicWidth() * 1.5),
                        drawable.getIntrinsicHeight());
                button.setCompoundDrawables(drawable, null, null, null);

                // could modify the placement more here if desired
                // button.setCompoundDrawablePadding();
            }
        });
        return dialog;
    }
}

这篇关于为AlertDialog按钮图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆