How to use and style new AlertDialog from appCompat 22.1 and above

前端 未结 6 1517
北荒
北荒 2020-11-27 08:59

I am trying to migrate from default android AlertDialog to the new one included in appCompat-22.1 So far I understand you only have to import android.sup

6条回答
  •  醉梦人生
    2020-11-27 09:33

    If you want to use the new android.support.v7.app.AlertDialog and have different colors for the buttons and also have a custom layout then have a look at my https://gist.github.com/JoachimR/6bfbc175d5c8116d411e

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
    
        View v = inflater.inflate(R.layout.custom_layout, null);
    
        initDialogUi(v);
    
        final AlertDialog d = new AlertDialog.Builder(activity, R.style.AppCompatAlertDialogStyle)
                .setTitle(getString(R.string.some_dialog_title))
                .setCancelable(true)
                .setPositiveButton(activity.getString(R.string.some_dialog_title_btn_positive),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                doSomething();
                                dismiss();
                            }
                        })
                .setNegativeButton(activity.getString(R.string.some_dialog_title_btn_negative),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dismiss();
                            }
                        })
                .setView(v)
                .create();
    
        // change color of positive button         
        d.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                Button b = d.getButton(DialogInterface.BUTTON_POSITIVE);
                b.setTextColor(getResources().getColor(R.color.colorPrimary));
            }
        });
    
        return d;
    }
    

提交回复
热议问题