简体   繁体   中英

App crashing when calling setContentView(R.layout.activity_main); for the second time

In my app. It first starts off by loading a.xml file called activity_main.xml. Then it changes the view to a class (gamedraw). After the program runs I want it to load the same.xml file that is used at the beginning, but it crashes when I use setContentView(R.layout.activity_main);

So the first time I load the view it works, then I change views, then at the end of the program I want it to load the first view again but it crashes

public class MainActivity extends Activity {

//declare class Gamedraw
private GameDraw gameDraw;



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


    gameDraw = new GameDraw(this, size);

    //set view to activity main
    setContentView(R.layout.activity_main);
}

public void startGame(View v) {

    //set view to gamedraw
    setContentView(gameDraw);
}


public void setViewActivity(){


    setContentView(R.layout.activity_main); //this line crashes the app

}

}

So first it loads: setContentView(R.layout.activity_main);

2nd it loads: setContentView(gameDraw);

3rd it loads: setContentView(R.layout.activity_main);

First and second work perfectly, but when it tries to load the activity_main at the end, the app crashes

this is badpractise, if you want to change views but stay within the same activity i recommend that you use fragments for the two views which you swap between.

In theory it should be possible to setContentview multiple times, but it requires you to call it from mainthread, which is probably the reason for the crash. It is irrelevant though as it is highly inefficient to do it this way.

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