TheHamstring
TheHamstring

Reputation: 732

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();
}

Upvotes: 4

Views: 688

Answers (3)

Kartihkraj Duraisamy
Kartihkraj Duraisamy

Reputation: 3221

May be still your R.layout.activity_myactivity is the controllable Contentview in your activity.

So you have to define your new layout as setContentView.

or you mentioned it is a Dialog box.

So you can add a content view for a dialog like the following,

Dialog d = new Dialog (this);
d.setContentView(your inflated view);

Upvotes: 0

TheHamstring
TheHamstring

Reputation: 732

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.

Upvotes: 1

Mehul Ranpara
Mehul Ranpara

Reputation: 4255

use this way...

public class myactivity extends Activity{

    @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(new OnClickListener()
       {

                public void onClick(View v) 
                {
                       Toast.makeText(myactivity.this, "The Start button was clicked.", Toast.LENGTH_LONG).show();
                }
       });


}

Upvotes: 0

Related Questions