City Techno
City Techno

Reputation: 151

Button state across different layouts in one activity?

I have 2 buttons to switch between 2 layouts in the same activity: clicking button1 on layout1, it goes to layout 2 (using setContentView). On layout2, clicking button2, it goes back to layout1. Then button1 is no longer responding OnClickListener. I looked into "Input Events" but still couldn't figure it out. What happened and how to fix it?

Thanks in advance!

Button submitBtn;
Button backBtn;
submitBtn = (Button)findViewById(R.id.button1); //on layout1
backButn = (Button)findViewById(R.id.button2);  //on layout2
submitBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
          setContentView(R.layout.layout2);
                    }
    });
backBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
          setContentView(R.layout.layout1);
                   }
    });

Upvotes: 1

Views: 269

Answers (2)

OleGG
OleGG

Reputation: 8657

You should re-assign listeners when you switch layout, cause when you're calling setContentView old view is destroyed, and new components are created.

Upvotes: 1

jtt
jtt

Reputation: 13541

You MUST set the contentview when it is time to change the layout, otherwise the views will be null.

Upvotes: 0

Related Questions