Question

I want to use the Android device back/return button to switch to a previous layout in my application, but only for specific layouts. All other cases should use the buttons normal close application function. This is to save space on the screen for an obvious "go back to the screen before this" button.

So far I came up with this simple solution:

int screenid=0;

public void ButtonClickN(View v)
{
    setContentView(R.layout.ScreenX);
    screenid=3;
}

public void onBackPressed()
{
    if(screenid==2) // screen z
    {
        setContentView(R.layout.ScreenY);
        screenid=1;
        return;
    }
    if(screenid==3) // screen x
    {
        setContentView(R.layout.ScreenZ);
        screenid=2;
        return;
    }

    finish(); // all other cases button works as normal
}

But I feel that this is not the best way to do this, as there might be something inbuilt to make it even simpler. Say, comparing layouts by name to remove the integer, or sliding the layouts from left to right...

Another way that works is to use Intent to make the new screen in another activity. It draws the new layout over the older one:

public void ButtonClickN(View v)
{
    Intent i3 = new Intent(view.getContext(), ActivityX.class);
    startActivityForResult(i3, 0);
}

This makes the Android back button work as before, but requires making a new class for every screen

public class ActivityX extends Activity

which onCreate calls:

setContentView(R.layout.ScreenX);

and requires additional declaration in the AndroidManifest.xml

<activity android:name=".ActivityX"></activity>

Clearly too much of a hassle in comparison to the first solution. It also generates an overlapping effect in the emulator, which I want to avoid. So far the effect doesn't appear on my Samsung Galaxy Y (GT-S5360), but who knows what it will be on other devices.

So my question, is there a better/simpler way to do selective use of the Android back button? Or switch between fullscreen layouts more efficiently?

Was it helpful?

Solution

Evidently keeping ID integer of which screen is currently in use the simplest solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top