Добавить кнопку переключателя в строке заголовка Alert Dialog в Android

Как добавить кнопку переключателя в строке заголовка диалогового окна предупреждения? В качестве примера смотрите скриншот параметров Wi-Fi. Как вы можете видеть, в заголовке Wi-Fi есть кнопка переключения внутри заголовка. Можно ли создать собственный диалог предупреждений, чтобы добавить кнопку переключения внутри строки заголовка диалога предупреждений? Код, приведенный ниже, предназначен для снимка экрана № 2, и я пометил его там, где я хочу, чтобы он был добавлен. Пожалуйста, помогите мне и направьте меня в правильном направлении.

                        alertDialogBuilder = new AlertDialog.Builder(context);
                        alertDialogBuilder.setTitle("Recording Timer");
                        LinearLayout LL = new LinearLayout(context);
                        LL.setFocusable(true);
                        LL.setFocusableInTouchMode(true);
                        LL.setOrientation(LinearLayout.HORIZONTAL);
                        final TextView secondsTextView = new TextView(context);
                        final TextView minutesTextView = new TextView(context);
                        final TextView hoursTextView = new TextView(context);
                        secondsTextView.setText("seconds");
                        minutesTextView.setText("minutes");
                        hoursTextView.setText("hours");
                        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                        lp.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
                        lp.setMargins(0, 15, 0, 0);
                        LL.setLayoutParams(lp);
                        LinearLayout.LayoutParams lp11 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                        lp11.setMargins(79, 0, 0, 0);
                        LL.addView(hoursTextView, lp11);
                        LinearLayout.LayoutParams lp22 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                        lp22.setMargins(107, 0, 0, 0);
                        LL.addView(minutesTextView, lp22);
                        LinearLayout.LayoutParams lp33 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                        lp33.setMargins(98, 0, 0, 0);
                        LL.addView(secondsTextView, lp33);
                        LinearLayout LL1 = new LinearLayout(context);
                        LL1.setOrientation(LinearLayout.HORIZONTAL);
                        secondsPicker = new NumberPicker(context);
                        minutesPicker = new NumberPicker(context);
                        hoursPicker = new NumberPicker(context);
                        secondsPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                            @Override
                            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                                if(newVal==0 && minutesPicker.getValue()==0 && hoursPicker.getValue()==0) {
                                    alertDialog1.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
                                } else {
                                    alertDialog1.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
                                }
                            }
                        });
                        minutesPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                            @Override
                            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                                if(newVal==0 && secondsPicker.getValue()==0 && hoursPicker.getValue()==0) {
                                    alertDialog1.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
                                } else {
                                    alertDialog1.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
                                }
                            }
                        });
                        hoursPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                            @Override
                            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                                if(newVal==0 && minutesPicker.getValue()==0 && secondsPicker.getValue()==0) {
                                    alertDialog1.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
                                } else {
                                    alertDialog1.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
                                }
                            }
                        });
                        secondsPicker.setMaxValue(59);
                        secondsPicker.setMinValue(0);
                        minutesPicker.setMaxValue(59);
                        minutesPicker.setMinValue(0);
                        hoursPicker.setMaxValue(23);
                        hoursPicker.setMinValue(0);
                        if (timedRecordingIsOn  || timedRecordingDialogOpened) {
                            secondsPicker.setValue(secondsNumberPickerInt);
                            minutesPicker.setValue(minutesNumberPickerInt);
                            hoursPicker.setValue(hoursNumberPickerInt);
                        }
                        timedRecordingDialogOpened = true;
                        LinearLayout.LayoutParams lp110 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                        lp110.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
                        lp110.setMargins(0, 40, 0, 0);
                        LL1.setLayoutParams(lp110);
                        LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                        lp1.setMargins(52, 0, 0, 0);
                        LL1.addView(hoursPicker, lp1);
                        LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                        lp2.setMargins(62, 0, 0, 0);
                        LL1.addView(minutesPicker, lp2);
                        LinearLayout.LayoutParams lp3 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                        lp3.setMargins(72, 0, 0, 0);
                        LL1.addView(secondsPicker, lp3);
                        RelativeLayout relativeLayout1 = new RelativeLayout(context);
                        relativeLayout1.addView(LL);
                        relativeLayout1.addView(LL1);
                        alertDialogBuilder.setView(relativeLayout1);
                        DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case DialogInterface.BUTTON_POSITIVE:
                                        secondsNumberPickerInt = secondsPicker.getValue();
                                        minutesNumberPickerInt = minutesPicker.getValue();
                                        hoursNumberPickerInt = hoursPicker.getValue();
                                        timeRecordingInMilliSeconds = (hoursPicker.getValue() * 3600000) + (minutesPicker.getValue() * 60000) + (secondsPicker.getValue() * 1000);
                                        timedRecordingIsOn = true;
                                        timedRecordingDialogOpened = false;
                                        timedRecordingTextView.setText("Timer set for: " + (hoursPicker.getValue() == 0 ? "00" : hoursPicker.getValue()) + ":" + (minutesPicker.getValue() == 0 ? "00" : minutesPicker.getValue()) + ":" + (secondsPicker.getValue() == 0 ? "00" : secondsPicker.getValue()));
                                        timedRecordingTextView.setVisibility(View.VISIBLE);
                                        //  button.performClick();
                                        break;
                                    case DialogInterface.BUTTON_NEGATIVE:
                                        if (timedRecordingIsOn) {
                                            timedRecordingIsOn = false;
                                            timedRecordingTextView.setVisibility(View.INVISIBLE);
                                        }
                                        timeRecordingInMilliSeconds = 0;
                                        secondsNumberPickerInt = 0;
                                        minutesNumberPickerInt = 0;
                                        hoursNumberPickerInt = 0;
                                        timedRecordingDialogOpened = false;
                                        break;
                                }
                            }
                        };
                        alertDialogBuilder.setPositiveButton("SET TIMER", dialogClickListener);
                        if (timedRecordingIsOn) {
                            alertDialogBuilder.setNegativeButton("CANCEL TIMER", dialogClickListener);
                        } else {
                            alertDialogBuilder.setNegativeButton("CANCEL", dialogClickListener);
                        }
                        alertDialog1 = alertDialogBuilder.create();
                        alertDialog1.setOnCancelListener(
                                new DialogInterface.OnCancelListener() {
                                    @Override
                                    public void onCancel(DialogInterface dialog) {  //When you touch outside of dialog bounds, the dialog gets canceled and this method executes.
                                        timeRecordingInMilliSeconds = 0;
                                        secondsNumberPickerInt = 0;
                                        minutesNumberPickerInt = 0;
                                        hoursNumberPickerInt = 0;
                                        timedRecordingDialogOpened = false;
                                    }
                                }
                        );
                        alertDialog1.show();
                        LL.requestFocus();
                        secondsPicker.clearFocus();
                        if(!timedRecordingIsOn && savedInstanceState!=null) {
                            alertDialog1.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
                        }
                        if(savedInstanceState!=null) {
                            if(secondsNumberPickerInt==0 &&  minutesNumberPickerInt ==0 && hoursNumberPickerInt == 0) {
                                alertDialog1.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
                            }

4 ответа

Решение

Примечание. Выполните любой из методов & MainActivity.this замените вашим контекстом.

Если вам нужен код Java, следуйте этому

    final AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
            dialog.setCancelable(false);
            final TextView titleTextView = new TextView(MainActivity.this);
            titleTextView.setText("Title");
            titleTextView.setTextColor(Color.RED);
            Switch switchval=new Switch(MainActivity.this);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)button.getLayoutParams();
            params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            switchval.setLayoutParams(params);
            RelativeLayout relative=new RelativeLayout(MainActivity.this);
            relative.addView(titleTextView);
            relative.addView(switchval);
            dialog.setCustomTitle(relative);
            /*Your Numberpickerview example is following*/
            //dialog.setView(yourcustomview);
            dialog.create().show();

-------------------------------------------------- ------------------------------

Введите XML: если вы хотите XML-код, следуйте этому

      final AlertDialog.Builder dialog1 = new AlertDialog.Builder(MainActivity.this);
            dialog1.setCancelable(false);
            dialog1.setCustomTitle(getLayoutInflater().inflate(R.layout.btn_share,null));
            //dialog1.setView(/*Your number picker view*/);
            dialog1.create().show();

btn_share.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Title"
    android:paddingLeft="10dp"
    android:layout_gravity="center"
    android:textColor="@color/colorAccent"/>

 <Switch
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignParentEnd="true"
   android:layout_alignParentRight="true"
   android:layout_marginRight="15dp"/>
</RelativeLayout>

Попробуйте реализовать один файл макета и раздувать, когда диалоговое окно оповещения открыто, и дать кнопку переключения в этом макете

final Dialog dialog = new Dialog(getContext());
        dialog.setCancelable(false);
        dialog.setContentView(R.layout.your_dialog_layout);
        dialog.setTitle("Dialog Title");

        //views inside your layout declare and cast here
        //e.g. final Button btn = (Button)dialog.findViewById(R.id.btn);


        //after all view casting and onClickListeners show your dialog
        dialog.show();

Мое предложение для этого состоит в том, чтобы создать файл макета для настраиваемого диалогового окна и сделать так, это будет полезно.

 final Dialog dialog = new Dialog(getContext());
            dialog.setCancelable(false);
            dialog.setContentView(R.layout.your_dialog_layout);
            dialog.setTitle("Dialog Title");

            //views inside your layout declare and cast here
            //e.g. final Button btn = (Button)dialog.findViewById(R.id.btn);


            //after all view casting and onClickListeners show your dialog
            dialog.show();

Добавить кнопку переключателя в строке заголовка Alert Dialog в Android

Вы можете использовать пользовательский макет, который включает заголовок и текст, а затем скрыть реализацию по умолчанию.

    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.custom_dialog, null);
dialogBuilder.setView(dialogView);

Вы можете скрыть заголовок диалога, используя:

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
Другие вопросы по тегам