[英]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.它首先通过加载名为 activity_main.xml 的.xml 文件开始。 Then it changes the view to a class (gamedraw).然后它将视图更改为 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);程序运行后,我希望它加载开始使用的相同的.xml 文件,但是当我使用 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);
所以首先它加载: setContentView(R.layout.activity_main);
2nd it loads: setContentView(gameDraw);
第二次加载: setContentView(gameDraw);
3rd it loads: setContentView(R.layout.activity_main);
第三次加载: 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第一个和第二个工作完美,但是当它尝试在最后加载 activity_main 时,应用程序崩溃
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.理论上应该可以多次setContentview,但它需要你从主线程调用它,这可能是崩溃的原因。 It is irrelevant though as it is highly inefficient to do it this way.但这无关紧要,因为这样做效率非常低。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.