| Index | Android apps - Multiple Screens |
See AndroidStudio's tutorial on Intent.
| Define a second screen |
| Moving to from MainActivity to second screen |
| Accessing data across screens |
| Accessing the context |
In app/manifests/AndroidManifest.xml, there is already an 'activity' for 'MainActivity', as follows:
Add another for your second screen, called (in this case) 'Screen2'. (This should go before '<'MainActivity'/application>'.)
Now add a second screen layout. Right click on app/res/layout, then 'New', then 'Layout Resource file'. Specify a name of (for example) 'screen2layout'. You can copy stuff across from app/res/layout/activity_main if you want, altering the parts of the layout that you want to change. There is one thing that you must change, the "tools:context" in the bit at the top.
You also need to add the code to process the screen (in Java). Right click app/java/com.(the project name)/MainActivity, then 'New', then Java Class. Specify a name of 'Screen2' (this name is the one in the manifest).
In this new class ('Screen2'), here is the code after the packagae and imports:
Set up the necessary layout in app/res/layout/activity_main to action the move, perhaps a button, with an onClick of 'go2' (or whatever you want).
In app/java/com.(the project name)/MainActivity:
Note the name 'Screen2' in the intent statement.
So when you run the app, 'MainActivity' gets run. When you click on a button in 'MainActivity', 'Screen2' gets run. This will have an arrow in the title bar which means that the user can get back to 'MainActivity'.
The easiest way is probably to define the fields you want in app/java/com.(the project name)/MainActivity as 'public static', as global variables, before the 'onCreate' method but after the Class defintion, e.g.
This can then be accessed in 'MainActivity' as 'message', and in 'Screen2' as 'MainActivity.message'. Either can alter the field as well as reading it.
In the app/java/com.(the project name)/MainActivity, you sometimes use 'MainActivity.this', e.g. in Toast. This won't work in 'Screen2'. Use 'getApplicationContext()' instead.
© Jo Edkins 2016 - Index to Android app index