警报对话框 - 如何实现取消和确定按钮

Jib*_*rge 0 java android android-alertdialog onclicklistener

我有这个警报对话框,它有这两个按钮(确定和取消)。我想知道我如何实施它。

因此,当您单击取消按钮时,它应该关闭警报对话框并返回到我当前所在的片段。如果我单击“确定”按钮,它应该替换当前的警报对话框并将其放置在另一个对话框中。

这是我下面用于确认的代码。java文件;

public class confirmation extends DialogFragment {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inf = getActivity().getLayoutInflater();
    final View theDIalog = inf.inflate(R.layout.example_xml, null);
    builder.setView(theDIalog);

AlertDialog dialog = builder.create();



    theDIalog.findViewById(R.id.makeaTransferOk).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getActivity(), "Okay button is clicked", Toast.LENGTH_SHORT).show();
        }
    });


    theDIalog.findViewById(R.id.makeaTransferCancel).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });

    return dialog;
}
}
Run Code Online (Sandbox Code Playgroud)

这是我的example_xml 代码;

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffc0c0c0">

<Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Cancel"
                android:id="@+id/makeaTransferCancel"/>

<Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="OK"
                android:id="@+id/makeaTransferOk"/>

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

请有人可以帮助我

Moh*_*man 5

针对您上面提到的功能尝试使用此代码:

AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
            builder1.setMessage("Write your message here.");
            builder1.setCancelable(true);
            builder1.setPositiveButton("Ok",
                    new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
            //put your code that needed to be executed when okay is clicked
            dialog.cancel();


            }
            });
            builder1.setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });

            AlertDialog alert11 = builder1.create();
            alert11.show();
Run Code Online (Sandbox Code Playgroud)