在对话框显示后,更改警报对话框的正按钮文字。

问题描述 投票:0回答:1

我有一个警报对话框,里面有一个微调器,我想根据微调器的位置改变正按钮的文字。我想根据微调器的位置改变正面按钮的文字。

mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {

if (position == 0) {

/////
// I have access to the dialog object here and need to change the positive button text 
////

}


@Override
public void onNothingSelected(AdapterView<?> parentView) {
          // your code here
}

});
android android-alertdialog
1个回答
0
投票

我是这样做的。

声明按钮 我的类

MaterialButton positiveBtn,negativeBtn;

创建我的函数并初始化我的按钮

void alertDialog(){
        AlertDialog.Builder dialogBuilder = new 
        AlertDialog.Builder(requireActivity());
        LayoutInflater inflater = this.getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.test_layout, null);
        dialogBuilder.setView(dialogView);


        positiveBtn = dialogView.findViewById(R.id.btn_positive);
        negativeBtn = dialogView.findViewById(R.id.btn_negative);

        AlertDialog alertDialog = dialogBuilder.create();
        alertDialog.show();


        negativeBtn.setOnClickListener(v -> {

            positiveBtn.setText("Text 2 Positive ");

        });


    }

下面是test_layout

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_margin="16dp"
    android:layout_height="wrap_content">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/btn_positive"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Text 1 Positive "
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent">


    </com.google.android.material.button.MaterialButton>

    <com.google.android.material.button.MaterialButton
        app:layout_constraintTop_toBottomOf="@id/btn_positive"
        android:id="@+id/btn_negative"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Cancel "
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">


    </com.google.android.material.button.MaterialButton>

</androidx.constraintlayout.widget.ConstraintLayout>

在你的方案中,你已经有了自定义的Alert Dialog布局,只需声明变量,初始化并在spinner索引内设置文本。

这个答案的灵感来自于 此处

© www.soinside.com 2019 - 2024. All rights reserved.