Switch from the main.xml layout to another layout
I have a basic Android question here:
I have a main.xml layout that loads up when the app is launched. This page has a menu button that I'd like to (when clicked) send the user to another layout (about.xml).
I doubt this is the right. When clicked this command is kicked in:
setContentView(R.layout.about);
And it seems to work, I do see the about.xml page, but I cannot navigate back to the main.xml layout when I hit the BACK button on my Android device, the app just closes.
I doubt that this is the right way to navigate between xml layout files. Can you please help or point me to a page that spells this out for a 开发者_开发技巧computer programmer beginner like myself?
Thank you very much,
Pat
EDIT: Thanks for all the answers you helped point me in the right direction. In an effort to help future noob programmers like myself to understand Activities, here's a great simple tutorial that I found online that mapped it out for us beginners!
http://www.warriorpoint.com/blog/2009/05/24/android-how-to-switch-between-activities/
Do you have a separate activity for your about page? Generally for each screen you create a new activity. When you go to new screen , the new activity will be stacked over the first screen activity. When you click Back on android device, the previous activity will be popped up.
What you want to do is create a new Activity for every different screen. You create each new Activity as a new class and use Intents to move between them. This way you will use setContentView();
only once for each Activity. The Android website is full of great resources.
Your main activity has the contentview set to main.xml
and you have another about.xml
which should be set to another activity so that you can move from one activity to another using Intents. I suggest you to kindly go through the developer's website where you can find the usage of activity and intents.
When switching between layout like this you need to manage the back buttons behavior
here is a pseudocode example to use in your activities main class
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if((keyCode == KeyEvent.KEYCODE_BACK) && (secondary_layout_is_displayed))
{
displayPrimaryLayout();
// return true to let the system know we consumed the back button press
return true;
}
// return the default value
return super.onKeyDown(keyCode, event);
}
精彩评论