Search code examples
androidonclicklistenerbuttonclick

Android OnClickListener not firing for button on separate Layout


I have two different layouts. One is which loads while start of the Activity and the other which loads after running some checks and creates a custom dialog. The Dialog has a button in it to trigger, at this point in time, onclick has a Toast message so I can confirm that the button has been clicked. Unfortunately I can't able to get any response when the button is clicked. I've been all over the web and I can't quite find what I'm missing.

public class myactivity extends Activity{
    Dialog accesspopup;    

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

        View inflatedView = getLayoutInflater().inflate(R.layout.dialoglayout, null);
        final Button cabtn = (Button)inflatedView.findViewById(R.id.cb);
        cabtn.setOnClickListener(cListener);
    }

    private OnClickListener cListener = new OnClickListener() {
        public void onClick(View v) {
            //Log.d("HiThereActivity", "THIS IS DEBUG OUTPUT TO LOGCAT");
            Toast.makeText(myactivity.this, "The Start button was clicked.", Toast.LENGTH_LONG).show();
        }
    };

public void showPopup(){
    accesspopup = new Dialog(myactivity.this);
    accesspopup.setContentView(R.layout.pop_window);
    accesspopup.setCancelable(false);
    accesspopup.setTitle("Window Title");
    accesspopup.show();
}

Solution

  • I did some more searching around and found that I need to create the OnClickListener inside the method which I am using to build and display the Dialog and not in the OnCreate.