Images for AlertDialog buttons

后端 未结 6 1999
再見小時候
再見小時候 2021-01-11 14:19

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

6条回答
  •  温柔的废话
    2021-01-11 15:04

    As @aaronvargas said, use onShowListener. I will improve his answer a little bit, since for older/smaller devices the image overlaps the text. Here is the onShow code:

    @Override
    public void onShow(DialogInterface dialogInterface) {
        Button button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
        button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.your_img, 0, 0, 0);
        Utils.centerImageAndTextInButton(button);
    }
    

    Here is an utility function to center a left image and text inside a Button:

    public static void centerImageAndTextInButton(Button button) {
        Rect textBounds = new Rect();
        //Get text bounds
        CharSequence text = button.getText();
        if (text != null && text.length() > 0) {
            TextPaint textPaint = button.getPaint();
            textPaint.getTextBounds(text.toString(), 0, text.length(), textBounds);
        }
        //Set left drawable bounds
        Drawable leftDrawable = button.getCompoundDrawables()[0];
        if (leftDrawable != null) {
            Rect leftBounds = leftDrawable.copyBounds();
            int width = button.getWidth() - (button.getPaddingLeft() + button.getPaddingRight());
            int leftOffset = (width - (textBounds.width() + leftBounds.width()) - button.getCompoundDrawablePadding()) / 2 - button.getCompoundDrawablePadding();
            leftBounds.offset(leftOffset, 0);
            leftDrawable.setBounds(leftBounds);
        }
    }
    

    This last function uses the width of the Button to make the calculation, so you must check that you are calling this in the right place. That is, the width should be other than zero. In this case, calling it from onShow is the right place :).

提交回复
热议问题