Search code examples
androidandroid-activity

How to go back from second screen to first screen


How to switch layouts? First, I have a class Main where is onCreate (setContentView(R.layout.main);) and then I call, another class with command:

setContentView(secondClass);

In this class, I draw with Canvas and this work just fine. I also create button to go back in first "class" (R.layout.main), but I don't know how to do it.

Now my program is basic a graph shower. In first class you type your function and them second class draw it. But how to go back in first class to type another function. This "back" button or arrow witch every Android phone have, send me out of program not back on insert part.

In secondClass I can't create onCreate method, but I also tried the following and they didn't work:

Intent abc = new Intent("bla.bla.bla.FIRSTCLASS");

startActivity(abc);

and

Intent abc = new Intent(SecondClass.this,FirstClass.class);

startActivity(greNaPrvoOkno);

Solution

  • If you want to use a custom view (as I understood, you are extending the View class), you can do it in the following way;

    Consider you are showing the second class from your Main activity like this;

    setContentView(new SecondClass(getApplicationContext(), MainActivity.this));
    

    And you Second class is this (suppose);

    // I am using onClickListener to go back to main view. You do whatever you like.
    public class SecondClass extends View implements OnClickListener {
    
        // This is needed to switch back to the parent activity
        private Activity mParentActivity = null;
    
        public SecondClass(Context context, Activity parentActivity) {
            super(context);
    
            mParentActivity = parentActivity;   
            setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            // Set the Main view back here.
            mParentActivity.setContentView(R.layout.main);
        }
    
    }
    

    Disclaimer: This code will do what you have asked for, but may cause other problems.

    As advised by @Mudassir, you should use two different activities for two screens. It will give you better control, and your code will be easy to understand and maintain.