问题
I have 2 layouts.
The 1st loads (a WebView) fine when the program starts.
The 2nd one also loads (a simple layout) fine when user selects a menu item:
setContentView(R.layout.simple);
LinearLayout ll = (LinearLayout) findViewById(R.id.simple_layout);
All it does is display an image while processing something in the background. When processing is done, it attempts to switch back (via Handler) to the WebView it just obscured.
setContentView(R.layout.main);
The switching seems to occur but the webview is blank.
Why is that? Isn't setContentView()
enough to switch back to the 1st layout just as the switch to 2nd worked fine?
回答1:
The main problem here is that you shouldn't call setContentView() several times (as noted in the comments). Fragments are a good idea, but you can also use a ViewFlipper if your just tying to change between 2 views. Example taken from http://blog.kerul.net/2011/07/viewflipper-examplea-simple-flashcard.html
Button next,previous;
ViewFlipper vf;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
next = (Button) findViewById(R.id.Button01);
previous = (Button) findViewById(R.id.Button02);
next.setOnClickListener(this);
previous.setOnClickListener(this);
vf=(ViewFlipper)findViewById(R.id.ViewFlipper01);
}
//@Override
public void onClick(View v) {
if (v == next) {
vf.showNext();
}
if (v == previous) {
vf.showPrevious();
}
}
}
The reason your screen is blank is because you'll have to re-init your webview again. If you were to call setContentView() several times, you have to re get your findViewByIds and all that. List view included.
回答2:
I use this method: In main program:
private LinearLayout mainview;
private LinearLayout playerview;
In onCreate:
LayoutInflater inflater = LayoutInflater.from(this);
setContentView(R.layout.main);
mainview = (LinearLayout) this.findViewById(R.id.main);
playerview = (LinearLayout) inflater.inflate(R.layout.player, null);
Then you can call
setContentView(mainview);
and
setContentView(playerview);
whenever you want. All you need is two layout xml files, one for each layout. This is much simpler than Fragments or other methods.
For some reason, I don't have to inflate the main view I start with, only the others. I think it's because setContentView() must inflate the view for you when it's called.
来源:https://stackoverflow.com/questions/11605437/setcontentview-is-not-enough-to-switch-between-layouts