porthfind
porthfind

Reputation: 1619

Android: Navigation Back using same activity with toolbar

I have an activity with differents layouts. Every time I want to go from one layout to another I use the Visibility property. But I have a toolbar and I don't know how to set the navigation back because I have always the same activity.

In a normal situation with more activities I would use the property android:parentActivityName, but in this situation I can't because is the same activity.

Part of my code:

 <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">

<!-- SIGN-IN SCREEN -->
<LinearLayout android:id="@+id/screen_sign_in" style="@style/LLScreen">
    <TextView style="@style/GameTitle" />
    <TextView style="@style/GameBlurb" />

    <com.google.android.gms.common.SignInButton android:id="@+id/button_sign_in"
        style="@style/SignInButton" />
</LinearLayout>

<!-- MAIN SCREEN -->
(...)

Code of the visibility I use to change screen:

void switchToScreen(int screenId) {
        // make the requested screen visible; hide all others.
        for (int id : SCREENS) {
            findViewById(id).setVisibility(screenId == id ? View.VISIBLE : View.GONE);
        }

How can I resolve this?

Upvotes: 0

Views: 47

Answers (1)

Jackey
Jackey

Reputation: 3234

Your main problem is that your method of showing "screens" is unconventional. Unlike the normal approaches of using Activities or Fragments, you're simply toggling View visibilities which doesn't have any built-in history for what's been shown.

So, your only solution for this approach is to build your own cache of what's been shown.

This is easily done with any data type, like a List. For this answer, I'll use a List as an example.

So first, create an instance of a List to store the history of your screens inside of the Activity:

List<Integer> listOfScreens = new ArrayList<Integer>();

Next, make sure to add to this list when you switch screens:

listOfScreens.add(screenId);
switchToScreen(screenId);

This way, you'll add the new screen to the list and then switch to the proper screen.

Finally, in your Navigation Up and onBackPressed() code, simply remove the last screen on the list and switch again.

@Override
public void onBackPressed() {
    listOfScreens.remove(listOfScreens.size()-1);
    switchToScreen(listOfScreens.get(listOfScreens.size()-1));
}

You'll remove the last item in the list which is the current screen, then switch the visibility back to the previous screen.

I've shown the code to do this in the onBackPressed() method, so do the same for your Up Navigation in your ToolBar.

Upvotes: 2

Related Questions