-2

So I have two layouts and I switch to the second layout when the ImageButton is pressed. On my nexus 6, how do I keep the first layout running so when I'm on the second layout and press back it would show the first layout?

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageButton ImageButton = (ImageButton) findViewById(R.id.image);

        ImageButton.setBackgroundColor(1);

        ImageButton.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view)
            {

                setContentView(R.layout.layoutsecond);
            }
        });



    }
}
PHPirate
  • 7,023
  • 7
  • 48
  • 84
asdwe
  • 23
  • 5
  • You can use 2 fragments for your task. Add 2nd fragment when you press a button and when you'll press back the previous fragment will automatically be shown. – Shadab Ansari Apr 24 '16 at 00:57
  • 1
    As mentioned on your previous question, changing layouts like that isn't really a good idea. Use another navigation pattern - like `Fragment`s, or multiple `Activities` - where the state will be handled for you. Otherwise, you need to take care of re-initializing all of your `View`s after each layout change. – Mike M. Apr 24 '16 at 00:58

1 Answers1

0

General idea, though horrible advice. Best to use Fragments and take advantage of the back stack

Start with a List<Integer>.

Store your first view on it

list.add(R.layout.view1);

Set your content view in onCreate and increment the position of the layout you are at.

int position = 0; // make this a field variable 
setContentView(list.get(position++));

Increment and add more layout IDs when you call setContentView again.

list.add(R.layout.view2);
setContentView(list.get(position++));

Implement onBackPressed to go back. Be careful about out of bounds exceptions, though.

setContentView(list.get(--position));

If you want to implement a feature to go forward, then

setContentView(list.get(++position));
Community
  • 1
  • 1
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245