简体   繁体   中英

How am I supposed to use setcontentview(r.layout.activity_main) Multiple times

this is my below code i want to switch between activity_main and activity_second multiple times but it is giving me error

public class MainActivity extends ActionBarActivity {

    Button buttonMain, buttonSecond;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        buttonMain = (Button) findViewById(R.id.buttonMain);
        buttonSecond = (Button) findViewById(R.id.buttonSecond);

        buttonMain.setOnClickListener(new OnClickListener() {

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

        buttonSecond.setOnClickListener(new OnClickListener() {

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

            }
        });

    }

}

When you call setContentView() , the view hierarchy that is displayed in the activity is replaced with a new one. Therefore the buttons you had in the previous view are gone too, together with their click listeners. So after calling setContentView() , you need to refresh any view references with findViewById() and reset any click listeners.

For more Android-y view hierarchy replacement at runtime, consider using fragments, with one fragment for your activity_main layout and another for your activity_second.

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