简体   繁体   中英

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

切换布局时,应重新分配侦听器,原因是在调用setContentView时会破坏旧视图,并创建新组件。

您必须在更改布局时设置contentview,否则视图将为null。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM