android – AlertDialog按钮的图像

是否可以在AlertDialog的正,负和中性按钮中添加drawable?如果是,那怎么样?

解决方法:

由于不推荐使用onPrepareDialog,因此您可以使用onShowListener.

你也应该设置Drawable边界,或者它将被放置在最左边.

下面的代码输出

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性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...