View.onClickListner not called from other class

2019-07-17 16:21发布

问题:

With ref to my previous question in button not shown in alertDialog

I am creating a class which extends AlertDialog. In the class I am setting the content from xml which has buttons, but my button is not responding. my custom alert java file is

public class DateTimeDialog extends AlertDialog{

    Date date;
    String title;
    View.OnClickListener listner;
    protected DateTimeDialog(Context context, String title, Date date ) {
        super(context, android.R.style.Theme_Holo_Light_Dialog);
        // TODO Auto-generated constructor stub
        this.title = title;
        this.date = date;
    }

    public void initListener(View.OnClickListener listner){
        this.listner = listner;
    }

    @Override
    public void onCreate(Bundle savedInstanceState){
        //super.onCreate(savedInstanceState);
        setContentView(R.layout.date_time_picker);

        setTitle(title);

        Button dialogButtonOK = (Button) findViewById(R.id.btn_ok);
        // if button is clicked, close the custom dialog
        dialogButtonOK.setOnClickListener(listner);

        Button dialogButtonCancel = (Button) findViewById(R.id.btn_cancel);
        // if button is clicked, close the custom dialog
        dialogButtonCancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View dialog) {
                // TODO Auto-generated method stub

            }
        });


    }

My method calling this class is

final DateTimeDialog dateTimeDialog = new DateTimeDialog(context, "Title", date);
           dateTimeDialog.show();
           dateTimeDialog.initListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    //done something
                }
            });

problem is my ok button is not called when clicked but cancel is called. I don't know where i am getting wrong.Please help!!!!

回答1:

Try this:

public void initListener(View.OnClickListener listner){
    this.listner = listner;
    Button dialogButtonOK = (Button) findViewById(R.id.btn_ok);
    dialogButtonOK.setOnClickListener(listner);
}