-1

I have a single activity which has two buttons on it .each button opens a new layout .now if i will press back my application will close .but i want to return on Mainactivity and if the user presses back again then app is closed and if he does not press and goes to the second layout and press back then app should not get closed. the condition should be if the user is on Mainactivity and he presses back button then the application closes. I came up with an idea on onBackPress method if i could set this condition

if (k==1 && Its not a Mainactivity(or the user is not inside a Mainactivity)) {//I dont know how to check for that 

    Intent i = new Intent(this,Mainactivity.class);
    startActivity(i);
    this.finish();
} else if (k==1 && Its a Mainactivity(or the user is inside a Mainactivity)) { 
  this.finish(); //then i just want to close the application,I dont know this.finish() ,It does not close the app but still it runs in background 
}

If u guys want to see my code here it is a simple example of what i am trying to achieve:-

public class MainActivity extends AppCompatActivity {

    Button btn1,button2;              //Creating button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);
           btn1= (Button)findViewById(R.id.btn1);      //finding button1
           button2=(Button)findViewById(R.id.button2); //finding button2 
           btn1.setOnClickListener(new View.OnClickListener() {

             @Override
             public void onClick(View v) {

               setContentView(R.layout.btn1);           

            }
        });


 button2.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

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

  }
}

Please help me.

PEHLAJ
  • 9,980
  • 9
  • 41
  • 53
Frankruss
  • 33
  • 8
  • what u mean by (I dont know this.finish() ,It does not close the app but still it runs in background)?? – jagapathi May 18 '17 at 21:01
  • i want the app to close but it just closes the session .I know that is the default behaviour of Android app.So i take it back. Do u have a solution for my prob – Frankruss May 18 '17 at 21:06
  • finish kills the app (i dont get the point session came to picture) (what make u think app is still alive)? – jagapathi May 18 '17 at 21:09

5 Answers5

2

In onBackPressed(), just check the value of k. If the value of k is 1 or 2, then call setContentView(R.layout.activity_main) again to show the main layout otherwise call super.onBackPressed() to close the MainActivity.

You need to call method initializeButtons() every time after setting activity_main layout to get the reference of buttons from layout as well as adding onClick listeners.

TRY THIS:

public class MainActivity extends AppCompatActivity {

    Button button1, button2;

    int k = 0;

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

        initializeButtons();
    }

    public void initializeButtons() {
        button1 = (Button) findViewById(R.id.btn1);
        button2 = (Button) findViewById(R.id.button2); 

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                k = 1;
                setContentView(R.layout.btn1);           
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                k = 2;
                setContentView(R.layout.btn2);
            }
        });
    }

    @Override
    public void onBackPressed() {

        if (k == 1 || k == 2) {
            k = 0;
            setContentView(R.layout.activity_main);
            initializeButtons();
        } else {
            super.onBackPressed();
        }
    }
}

UPDATE:
As per discussion in comment section, If you want to open Mainctivity again during back press, then override and update onBackPressed() as below:

    @Override
    public void onBackPressed() {

        if (k == 1 || k == 2) {
            k = 0;

            Intent i = new Intent(this, MainActivity.class);
            startActivity(i);
        } else {
            super.onBackPressed();
        }
    }

Hope this will help~

Ferdous Ahamed
  • 21,438
  • 5
  • 52
  • 61
  • Nice Logic!!.. but if click button 1 and it opens a new layout and i press back and instead of pressing back again i go to button2 then it wont open thr respective layout.Here your logic fails.any idea how could i achieve that. – Frankruss May 18 '17 at 20:23
  • It will open layout btn2, as we set it from button2 onclick method....button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { k = 2; setContentView(R.layout.btn2); } }); – Ferdous Ahamed May 18 '17 at 20:38
  • bt it is not opening.see my both xml files b1n1.xml its a blank layout and other btn2.xml has a textview – Frankruss May 18 '17 at 20:42
  • nothing fancy here i also cant understan i looked through but its not opening. Please help me. – Frankruss May 18 '17 at 20:43
  • I did as u said u can try and check it does not work when opening second button without exiting the app – Frankruss May 18 '17 at 20:52
  • 1
    It worked.Thank u so much! U r super genius.But can u explain why just adding it to a method worked and previously it was not working. – Frankruss May 18 '17 at 21:14
  • Because when you set again layout_main, you have to get the reference of buttons again and need to set listener again. Because your layout is just changing. Just to reduce the common code i make an method. – Ferdous Ahamed May 18 '17 at 21:16
  • you have to do this for all other layout if they contains button or others views to get the proper behavior. – Ferdous Ahamed May 18 '17 at 21:18
  • Btw, happy to know that its working. Please mark my answer as right answer and give an upvote if my answer seems useful and helpful to you. Thanks in advance :) – Ferdous Ahamed May 18 '17 at 21:19
  • wht if i want this public void onBackPressed() { if (k == 1 || k == 2) { k = 0; Intent i = new Intent(this,MainActivity.class); startActivity(i); initializeButtons(); } else { super.onBackPressed(); } }} I want to open mainactivty class its crashing – Frankruss May 18 '17 at 21:21
  • instead of opening a layout here i want to open a Mainactivity which contains other stuff .but app crashes when i presss back – Frankruss May 18 '17 at 21:24
  • Its happening because you are calling method initializeButtons(). Suppose you press button1, so your current layout is btn1. when you press back it will enter condition if (k == 1 || k == 2) {} and open new activity and then call method initializeButtons(). Inside this button when trying to get reference of button 1 and setting its listener it will crash because your current layout is btn1 and this layout does not contain any button with respective ids. – Ferdous Ahamed May 18 '17 at 21:30
  • Just remove line initializeButtons() from your condition. because you are starting another activity. – Ferdous Ahamed May 18 '17 at 21:32
  • 1
    I: got it i just forget to cancel my comment Thanks.buddy can u help me with this.......I marked ur answer and voted .Can u help me with this :-http://stackoverflow.com/questions/43967714/implementing-imageslider-gridview-with-picasso/43970973#43970973 – Frankruss May 18 '17 at 21:35
0

The default behaviour of onBackPressed() is to close the current Activity. In your case there is only one Activity i.e MainActivity in which you are changing the layout.

As you are changing the whole content anyways, you might as well create a new Activity and setContentView(R.layout.btn1) there. And in onClick() of the buttons start this new activity. You'll get the functionality you require.

Veneet Reddy
  • 2,707
  • 1
  • 24
  • 40
  • In my case it is different. i have 30 buttons each open a new layout ,so i dont want to create 30 activity.Thanks for help though!! – Frankruss May 18 '17 at 20:26
0

Your problem is that you should make separate layout for every activity. And when you click on the btn1, it will go to another activity.

But in your code you only change the content of the MainActivity.

So you should use Intent for moving between activities.

Like this:

Intent intent = new Intent (MainActivity.this, SecondAvtitity.class);

So the layout will change and when you press back button, app will go back to MainActivity.

And when you are in MainActivity and you press back button, the app will be closed.

For better explanation I have make an example app:

public class MainActivity extends AppCompatActivity {

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

    Button button1 = (Button) findViewById(R.id.button1);
    Button button2 = (Button) findViewById(R.id.button2);

    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            startActivity(intent);
        }
    });

    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, ThirdActivity.class);
            startActivity(intent);
        }
    });
 }
}
Hossein Seifi
  • 1,380
  • 11
  • 29
  • Bro i have single activity and 30 layouts.I dont want to create 30 activities more . – Frankruss May 18 '17 at 20:35
  • I know but my way is very easy and needs no code for back button. – Hossein Seifi May 18 '17 at 20:47
  • U r not understanding bro .I have a single activity and multiple layouts. How can i implement SecondActivity.class if i dont have second activity – Frankruss May 18 '17 at 20:49
  • I know what you mean. But there is a constructional problem in your way of coding. And that is : When you press back button, your code just changes the content of view and it does not read and does not re_execute the whole snippet of MainActivity. So in that time there is not any methods for the buttons ; and when you press the back button , your app will be closed. Is there any way to make the MainActivity be executed again from onBackPressed method? – Hossein Seifi May 18 '17 at 21:06
0

You can maintain a stack of all the previous layouts that were added. First add an instance variable:

Stack<Integer> layoutHistoryStack = new Stack<>();

Then, add these two methods:

    @Override
    public void onBackPressed() {
        if(layoutHistoryStack.size() == 1) {
            // the first layout that was added is shown. finish()
            layoutHistoryStack.pop();
            finish();
            return;
        }

        // pop() the current layout
        layoutHistoryStack.pop();
        // show the prev
        setContentView(layoutHistoryStack.peek(), false);


    }

    public void setContentView(@LayoutRes int layoutResID, boolean addToHistoryStack) {
        if(addToHistoryStack) layoutHistoryStack.add(layoutResID);
        super.setContentView(layoutResID);
    }

Then, replace every previous setContentView(R.id.layout) calls with setContentView(R.id.layout, true) i.e adding to your layoutHistoryStack.

Veneet Reddy
  • 2,707
  • 1
  • 24
  • 40
0

How about this one. It really works.

I have completed Ferdous's snippet:

public class MainActivity extends AppCompatActivity {

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

    Button button1 = (Button) findViewById(R.id.button1);
    Button button2 = (Button) findViewById(R.id.button2);

    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            k = 1;
            setContentView(R.layout.activity_second);
        }
    });

    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            k = 2;
            setContentView(R.layout.activity_third);
        }
    });
}

@Override
public void onBackPressed() {

    if (k == 1 || k == 2) {
        k = 0;
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    } else {
        this.finishAffinity();
    }
}

}
Hossein Seifi
  • 1,380
  • 11
  • 29