我正在尝试在MainActivity打开之前显示加载屏幕一段时间。我使用ViewSwitcher首先加载加载屏幕布局,延迟后,它切换到主布局。这一切都很好。
MainActivity中的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new LoadViewTask().execute();
}
private class LoadViewTask extends AsyncTask<Object, Object, Void>{
@Override
protected void onPreExecute(){
viewSwitcher = new ViewSwitcher(MainActivity.this);
viewSwitcher.addView(View.inflate(MainActivity.this, R.layout.loading_screen, null));
loadImg = (ImageView)findViewById(R.id.loadingLogo);
setContentView(viewSwitcher);
}
@Override
protected Void doInBackground(Object... params){
try{
synchronized(this){
int counter = 0;
while (counter <=4 ){
this.wait(850);
counter++;
}
}
}catch(InterruptedException e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result){
viewSwitcher.addView(View.inflate(MainActivity.this, R.layout.activity_main, null));
viewSwitcher.showNext();
initMainView(); //THIS INITIALIZES[SETS LISTENERS ETC] MY MAIN LAYOUT BUTTONS
}
}
问题是这个活动为结果启动了几个其他活动,当它们返回结果时,当我尝试访问activity_main布局中的任何元素时,我得到一个NullPointerException。我发现活动每次打开活动时都会尝试加载加载屏幕。我该如何防止这种情况?如何确保仅调用一次加载布局?
我在MainActivity的onActivityResult中尝试了这个。
if(requestCode == 2){
if(resultCode == Activity.RESULT_OK){
if(viewSwitcher.getDisplayedChild() == 0){
Log.d(MTAG, " Inside view switcher is displaying child 0 ");
viewSwitcher.showNext();
initMainView();
}
continueButton.setVisibility(View.VISIBLE); //NULLPOINTEREXCEPTION HERE
}
}
但这不起作用。我还是Android编程的新手,所以请尝试解释我做错了什么?