如何在自定义对话框中设置自定义按钮?

时间:2015-05-14 10:42:21

标签: android button alertdialog

我的对话框是一个自定义布局dialogbox_solution,带有一个标题和两个按钮。 这是仅包含主线的XML文件:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout>

    <TextView
        android:id="@+id/txtDiaMsg"
        />

    <TableLayout
        android:layout_below="@+id/txtDiaMsg">
        <TableRow>
            <Button
                android:id="@+id/yesButton"
                android:text=" YES "/>
            <Button
                android:id="@+id/noButton"
                android:text=" NO "/>
        </TableRow>
    </TableLayout>
</RelativeLayout>

如何以编程方式链接我的自定义正面按钮和负面按钮?

DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which){
                                    case DialogInterface.BUTTON_POSITIVE:
                                        //Yes button clicked
                                       // do something here
                                        break;

                                    case DialogInterface.BUTTON_NEGATIVE:
                                        //No button clicked
                                        break;
                                }
                            }
                        };
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        LayoutInflater li = getLayoutInflater();
                        View view = li.inflate(R.layout.dialogbox_solution, null);
                        builder.setView(view);
                        builder.show();

1 个答案:

答案 0 :(得分:3)

创建这样的东西......首先创建你的布局xml文件...例如:dialog.xml ...然后在下面的代码中随意调用它...

2

dialog.xml

 final Dialog myDialog = new Dialog(this);
 myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        myDialog.setContentView(R.layout.dialog);
        myDialog.setCancelable(false);
        Button yes = (Button) myDialog.findViewById(R.id.share);
        Button no = (Button) myDialog.findViewById(R.id.no);
        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Do your code here
            }
        });
        yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               //Do your code here
            }
        });

        myDialog.show();
        myDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    dialog.cancel();
                    return true;
                }
                return false;
            }
        });