简体   繁体   中英

Android: customize DialogPreference Ok/Cancel buttons

I cannot find a way to properly modify the Ok/Cancel buttons of the DialogPreference .

All the input dialogs in my app have the following button box:

在此处输入图片说明

This is what I can get in the DialogPreference :

在此处输入图片说明

not accetable, of course, as the buttons are swapped and with a horrible line in between.

What I do to apply the changes to the buttons is getting the Dialog int the showDialog method and setting a background to the layout:

public class RingtonePreference extends DialogPreference
{

    @Override
    protected void showDialog(Bundle state)
    {
        super.showDialog(state);

        Dialog d = getDialog();
        Utils.setAlertDialogButtons(getContext(), (AlertDialog)d, true);
    }

...

static public void setAlertDialogButtons(Context c, final AlertDialog alertDialog, final boolean hasNegative)
{
    try
    {
        int size = (int)c.getResources().getDimension(R.dimen.btn_size);
        TableRow.LayoutParams lp = new TableRow.LayoutParams(size, size);
        lp.setMargins(size/2, 5, size/2, 5);

        Button posBtn = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
        LinearLayout tr = (LinearLayout)posBtn.getParent();
        tr.setGravity(Gravity.CENTER);
        tr.setBackgroundResource(R.drawable.fixed_buttons_background);

        posBtn.setText("");
        posBtn.setLayoutParams(lp);
        posBtn.setBackgroundResource(R.drawable.btn_apply_selector);

        if (hasNegative)
        {
            Button negBtn = alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
            negBtn.setText("");
            negBtn.setLayoutParams(lp);
            negBtn.setBackgroundResource(R.drawable.btn_back_selector);
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
        Log.e("U", e.getMessage());
    }
}

I'm giving up but, before doing it, I ask here for help. Giving up means " leaving the original settings panel as it is " ( horrible ):

在此处输入图片说明

so, please, help :)

  1. Make sure you use the same theme for your standard app screens and Preferences screen to have consistent results.

  2. Untested but should work: If you want to change the look and feel of the bottom buttons bar, what you could do is:

    • Override setPositiveButtonText() and setNegativeButtonText() in DialogPreference to make them no-ops so Android will not show the standard "ok" and "cancel" buttons bar.

    • Then in your overriden showDialog() method, after retrieving the Dialog like you do now, cast it to AlertDialog and call setView() to pass your custom footer layout. It will be shown at the same place as the OK/Cancel buttons, below the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM