android - AlertDialog 按钮的图像

标签 android user-interface controls

是否可以将可绘制对象添加到 AlertDialog 的positivenegativeneutral 按钮?如果是,那么如何?

最佳答案

由于 onPrepareDialog 已弃用,您可以改用 onShowListener

您还应该设置 Drawable 边界,否则它将被放置在最左边。

下面代码的输出

Output of Code below

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;
    }
}

关于android - AlertDialog 按钮的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3679432/

相关文章:

android - 获取 EditTextPreference 值

user-interface - 程序员应该设计用户界面吗?

c# - 强制选项卡到扩展的 .net 控件中的下一个控件

android - 无法更改 RatingBar 的宽度和星星数

android - 查看未找到不变违规

android - 如何解决OpenCv版本4.1.2中Imgproc的错误?

python - 与 Flask 应用程序同时运行 GUI

C# 双缓冲?

delphi - 复合组件的选择框未正确绘制

oracle - 是否有其他方法可以在 pl/sql for 循环中表示 'next'?