Search code examples
androidbuttonback

Button to go back to the previous page


I want to make a button that allow user to go back to the previous page when click. Just work like the physical back button on the android device. What should I add to the java file?

here is the code(xml):

<Button
        android:id="@+id/button00"
        android:layout_width="80dp"
        android:layout_height="40dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="10dp"
        android:text="@string/st_pp"
        android:textColor="#01646d"
        android:background="#fef200"/>

here is the code(java):

bn00.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent it1 = new Intent(getApplicationContext(), Main.class);
                startActivity(it1);
            }

        });

Solution

  • To go back to previous activity use finish() method. But note that previous activity not contains finish() while you call current activity.

    Code :

    bn00.setOnClickListener(new OnClickListener(){
    
                @Override
                public void onClick(View arg0) {
    
                    finish();
                }
    
            });
    

    Using above code you can go to your previous activity. You can also call finish() in onKeyDown() method like..

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
           finish();
            return true;
        }
    
        return super.onKeyDown(keyCode, event);
    }