Gerrit Beuze
Gerrit Beuze

Reputation: 921

How to avoid AlertDialog positive button to become invisible?

My app uses android API 21 (android 5) with the Theme.Material.Light.DarkActionBar theme. In an AlertDialog I add positive, negative and neutral buttons. On small screens this can cause the positive to be hidden if the (translated!) button texts are too long to fit on the (portrait) screen. Previous versions of android did not have this problem (text was wrapped to make the buttons fit). The app will work OK if the neutral button is hidden, but I need the positive button to be visible at all times and regardless of translations. Is there any way to enforce this, other than adding "normal" buttons in the layout? Alt: is ther any way to check if buttons will fit? So I can at runtime decide not to use the neutral button?

Upvotes: 0

Views: 1213

Answers (2)

Gerrit Beuze
Gerrit Beuze

Reputation: 921

I found one solution that more or less works. In the onResume() method I modify the neutral button like so:

public void onResume() {
    super.onResume();
    final Button btn = ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_NEUTRAL);
    if (btn != null) {
        if (Build.VERSION.SDK_INT >= 21) {
            DisplayMetrics metrics = getResources().getDisplayMetrics();
            int maxWidth = (metrics.widthPixels / 3);
            btn.setSingleLine(false);
            btn.setMaxWidth(maxWidth);
            btn.setMaxLines(2);
            btn.setEllipsize(TextUtils.TruncateAt.END);
            // something in the above code reverts the allCaps
            btn.setAllCaps(true);
        }
}

Setting maxWidth works, but I have not found a way to accurately calculate the actual max width that would cause the positive button to disappear. The code above unconditionally limits to a third of the display width, which seems to work OK in my case.

Upvotes: 1

Sush
Sush

Reputation: 3874

The issue can be solved at all places by creating custom view ( Dialog with custom view )which will have buttons as the bottom. set onclick listeners to all and handle separately.

Upvotes: 0

Related Questions