取消按钮不工作 AlertDialog Android

Cancel Button is not working AlertDialod Android

在我的应用程序中,我创建了一个带有标题、列表视图项和取消按钮的警报对话框。我已经设置了 Item 单击列表中的每个项目。因此,如果用户单击项目,它将生成另一个带有标题、列表视图和取消的警报对话框。第一个 Alerdialog 的取消按钮工作正常。但是第二个 Alerdialog 的取消按钮不起作用。我不知道它背后的原因是什么。我已经实现了类似的代码。这是我的代码。

public class AlertDialogFragment extends DialogFragment{

private ListView listView1;
private ListView listView2;
private Button cancelButton1;
private Button cancelButton2;
private String[] companyName;
private String[] actionName;
private ArrayAdapter<String> adapter;

public AlertDialogFragment(){
        // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setCancelable(true);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogStyle);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.first_alertlist_contact, container, false);

        //Set Title Dialog
        getDialog().setTitle("Contact");

        //Button,ListView1 Initialization
        listView1=(ListView) rootView.findViewById(R.id.listView1);
        cancelButton1=(Button) rootView.findViewById(R.id.cancel_button1);

        // Defined Array values to show in ListView
        companyName = getResources().getStringArray(R.array.company_name);

        //Create and set Adepter TO ListView1
        adapter=new ArrayAdapter<String>(getActivity(), R.layout.first_alertlist_textstyle,android.R.id.text1,companyName);
        listView1.setAdapter(adapter);

        cancelButton1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });

       listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // ListView Clicked item index
                int itemPosition = position;

                if(itemPosition == 0)
                {
                    dismiss();
                    showDialog2();
                }

                if(itemPosition == 1)
                {
                    dismiss();
                    showDialog2();
                }
                if(itemPosition == 2)
                {
                    ....
                }
            }

        });
        return rootView;
    }

    private void showDialog2(){

        final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this.getActivity(), R.style.DialogStyle);
        LayoutInflater inflater = this.getActivity().getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.second_alertlist_contact, null);
        dialogBuilder.setView(dialogView);

        listView2 = (ListView) dialogView.findViewById(R.id.listView2);
        cancelButton2=(Button) dialogView.findViewById(R.id.cancel_button2);


        // Defined Array values to show in ListView
        actionName = getResources().getStringArray(R.array.contact_way);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(),
                R.layout.first_alertlist_textstyle, android.R.id.text1, actionName);

        listView2.setAdapter(adapter);

        listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                // ListView Clicked item index
                int itemPosition = position;

                if(itemPosition == 0)
                {
                    dismiss();
                    System.out.println("Hello");;
                }

               ...

            }

        });
        cancelButton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        dialogBuilder.show();


    }

}

这是我的 XML 第一个 AlertDialog

代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#FFFFFF"
android:layout_width="match_parent"
android:layout_height="match_parent">


    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="15dp"
        android:paddingBottom="15dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:text="Contact"
        android:gravity="center_horizontal"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:layout_gravity="center"
        android:textColor="#FFFFFF"
        android:background="#283593"/>

    <ListView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/listView1"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_gravity="center"
        >
    </ListView>

    <Button
        android:id="@+id/cancel_button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        android:text="Cancel"
        android:textColor="#FFFFFF"
        android:background="#283593"/>

   </LinearLayout>

和XML 第二次警报代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="15dp"
    android:paddingBottom="15dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:text="What do you want to do"
    android:gravity="center_horizontal"
    android:textAppearance="@style/TextAppearance.AppCompat.Large"
    android:layout_gravity="center"
    android:textColor="#FFFFFF"
    android:background="#283593"/>

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listView2"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:layout_gravity="center"
    >
</ListView>

<Button
    android:id="@+id/cancel_button2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="@style/TextAppearance.AppCompat.Medium"
    android:text="Cancel"
    android:textColor="#FFFFFF"
    android:background="#283593"/>

/**Just Implement the below code **/

companyName = getResources().getStringArray(R.array.company_name);

selectData(companyName);

private void selectData(final ArrayList<String> array_data)
{
    final Dialog dialog_data = new Dialog(context);

    dialog_data.requestWindowFeature(Window.FEATURE_NO_TITLE);

    dialog_data.getWindow().setGravity(Gravity.CENTER);

    dialog_data.setContentView(R.layout.custom_alertdialog);

    WindowManager.LayoutParams lp_number_picker = new WindowManager.LayoutParams();
    Window window = dialog_data.getWindow();
    lp_number_picker.copyFrom(window.getAttributes());

    lp_number_picker.width = WindowManager.LayoutParams.MATCH_PARENT;
    lp_number_picker.height = WindowManager.LayoutParams.WRAP_CONTENT;

    window.setGravity(Gravity.CENTER);
    window.setAttributes(lp_number_picker);



    TextView alertdialog_textview = (TextView) dialog_data.findViewById(R.id.alertdialog_textview);
    alertdialog_textview.setText("Contact");
    alertdialog_textview.setHint("Contact");

    Button dialog_cancel_btn = (Button) dialog_data.findViewById(R.id.dialog_cancel_btn);
    dialog_cancel_btn.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            if(dialog_data != null)
            {
                dialog_data.dismiss();
                dialog_data.cancel();
            }

        }
    });

    EditText filterText = (EditText) dialog_data.findViewById(R.id.alertdialog_edittext);
    ListView alertdialog_Listview = (ListView) dialog_data.findViewById(R.id.alertdialog_Listview);
    alertdialog_Listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    final ArrayAdapter<String>  adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_single_choice, array_data);
    alertdialog_Listview.setAdapter(adapter);
    alertdialog_Listview.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> a, View v, int position, long id)
        {
            actionName = getResources().getStringArray(R.array.contact_way);

            int itemPosition = position;

            if(itemPosition == 0)
            {
                selectData(actionName);
            }

            if(itemPosition == 1)
            {
                selectData(actionName);
            }
            if(itemPosition == 2)
            {
                ....
            }



            if(dialog_data != null)
            {
                dialog_data.dismiss();
                dialog_data.cancel();
            }
        }
    });

    filterText.addTextChangedListener(new TextWatcher()
    {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after)
        {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {

        }

        @Override
        public void afterTextChanged(Editable s)
        {
            adapter.getFilter().filter(s);
        }
    });

    dialog_data.show();
}

/*** custom_alertdialog.xml ***/

  <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/alertdialog_linearlayout"
   android:layout_height="wrap_content"
   android:layout_width="match_parent"
   android:background="@null">

  <LinearLayout
  android:layout_height="wrap_content"
  android:layout_width="match_parent"
  android:orientation="vertical"
  android:layout_marginTop="@dimen/dimen_20dp"
  android:background="@color/white">

  <TextView
      android:id="@+id/alertdialog_textview"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/select_state"
      android:textColor="@color/black"
      android:textSize="@dimen/text_size_16sp"
      android:layout_marginTop="@dimen/dimen_20dp"
      android:layout_marginLeft="@dimen/dimen_20dp"
      android:layout_marginStart="@dimen/dimen_20dp"
      android:layout_marginRight="@dimen/dimen_20dp"
      android:layout_marginEnd="@dimen/dimen_20dp"
      android:gravity="center"
      android:drawableLeft="@drawable/ic_launcher"
      android:drawableStart="@drawable/ic_launcher"
      android:drawablePadding="@dimen/dimen_10dp"/>

  <EditText
      android:id="@+id/alertdialog_edittext"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:ellipsize="end"
      android:textStyle="normal"
      android:textColorHint="@color/edittext_hint_color"
      android:textColor="@color/edit_profile_text_color"
      android:layout_marginLeft="@dimen/dimen_20dp"
      android:layout_marginStart="@dimen/dimen_20dp"
      android:layout_marginRight="@dimen/dimen_20dp"
      android:layout_marginEnd="@dimen/dimen_20dp"
      android:layout_marginTop="@dimen/dimen_10dp"
      android:layout_marginBottom="@dimen/dimen_10dp"
      android:maxLines="1"
      android:textCursorDrawable="@null"
      android:gravity="start"
      android:inputType="text"
      android:theme="@style/alertdialog_edittextTheme"
      android:layout_gravity="start" />

  <ListView
      android:id="@+id/alertdialog_Listview"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_marginLeft="@dimen/dimen_20dp"
      android:layout_marginStart="@dimen/dimen_20dp"
      android:layout_marginRight="@dimen/dimen_20dp"
      android:layout_marginEnd="@dimen/dimen_20dp"
      android:choiceMode="singleChoice"/>

  </LinearLayout>

   <Button
    android:id="@+id/dialog_cancel_btn"
    android:layout_width="@dimen/dimen_30dp"
    android:layout_height="@dimen/dimen_30dp"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:text="@string/X"
    android:textColor="@color/black"
    android:gravity="center"
    android:layout_alignParentTop="true"
    android:layout_marginRight="@dimen/dimen_10dp"
    android:layout_marginEnd="@dimen/dimen_10dp"
    android:layout_marginTop="@dimen/dimen_5dp"
    android:background="@drawable/round_button"/>

   </RelativeLayout>


    /**round_button**/

  <?xml version="1.0" encoding="utf-8"?>
 <shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="0dp"
android:shape="oval"
android:thicknessRatio="1.9"
android:useLevel="false" >

<solid android:color="@android:color/white" />

<size android:width="100dp"
    android:height="100dp"/>

<stroke android:width="1dp"
    android:color="@color/black"/>

由于我的声誉,我必须 post 将此作为答案而不是评论。但是,AlertDialog 是否包含列表视图? 所以在您的 AlertDialog 中,您将拥有

标题
列表视图
取消

如果是这种情况,我将编辑此 post 解决方案。您的代码非常古怪...所以我认为最好的办法是从头开始。

使用以下代码编辑

//Create a new builder and get the layout.
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
View builderView = getLayoutInflater().inflate(R.layout.alert_listview, null);

//Set the layout inside of the builder
builder.setView(builderView);

//Show the dislog
final AlertDialog alert = builder.show();

//Get the TextView, ListView, Button from the layout.
TextView alertTitle = (TextView) builderView.findViewById(R.id.alertTitle);
Button alertButton = (Button) builderView.findViewById(R.id.alertButton);
ListView alertListView = (ListView) builderView.findViewById(R.id.listView);

alertTitle.setText("YOU CAN SET THIS TO WHATEVER");

//Click the alert button from within the alert will dismiss the dialog box
alertButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        alert.dismiss();
    }
});

alert_listview.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="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:gravity="center"
        android:text="Title"
        android:id="@+id/alertTitle"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_below="@+id/alertTitle">
        <ListView
            android:layout_width="match_parent"
            android:id="@+id/listView"
            android:layout_height="0dip"
            android:layout_weight="1"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:id="@+id/alertButton"
            android:text="BUTTON"/>
    </LinearLayout>

</RelativeLayout>

这是对话框中的列表

//Create a new builder and get the layout.
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
View builderView = getLayoutInflater().inflate(R.layout.alert_listview, null);

//Set the layout inside of the builder
builder.setView(builderView);

//Show the dislog
final AlertDialog alert = builder.show();

List<String> arrayList = new ArrayList<String>();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
arrayList.add("6");
arrayList.add("7");
arrayList.add("8");
arrayList.add("9");
arrayList.add("10");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_expandable_list_item_1, arrayList);

//Get the TextView, ListView, Button from the layout.
TextView alertTitle = (TextView) builderView.findViewById(R.id.alertTitle);
Button alertButton = (Button) builderView.findViewById(R.id.alertButton);
ListView alertListView = (ListView) builderView.findViewById(R.id.listView);

alertListView.setAdapter(arrayAdapter);

alertTitle.setText("YOU CAN SET THIS TO WHATEVER");

//Click the alert button from within the alert will dismiss the dialog box
alertButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        alert.dismiss();
    }
});