Zizou
Zizou

Reputation: 1951

How to go back to previous class?

I created in my program back Button in my ActionListener I raised the activity that I want to return to it, but the problem that I when I pressed it restarts the activity. But I want him to have the same behavior as the button back of Android. now i use

final Button boutton = (Button) findViewById(R.id.back);
                boutton.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        Intent intent2 = new Intent(ResultActivity.this,
                                AppList.class);
                        startActivity(intent2);

                    }
                }); 
    }

Upvotes: 0

Views: 228

Answers (4)

Piotr Ślesarew
Piotr Ślesarew

Reputation: 2836

You can simply call getActivity().onBackPressed() if your code is in Fragment or onBackPressed() if your code is in Activity. Make sure that you do not override onBackPressed(). This solution is coherent. Override onBackPressed() will change behaviour of onClick method on your button.

final Button boutton = (Button) findViewById(R.id.back);
            boutton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    onBackPressed();
                }
            }); 
}

Upvotes: 1

hemantsb
hemantsb

Reputation: 2059

i think there is no use of firing intent

just call finish() that will do the trick for you.

See this, hope it will work


final Button boutton = (Button) findViewById(R.id.back);
            boutton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                   finish();

                }
            });

Upvotes: 0

Linga
Linga

Reputation: 10553

Simply finish() the current activity. It will go back to the previous activity

"the problem that I when I pressed it restarts the activity" which means, you finished() the previous activity.

So, don't use finish() in the previous activity, just finish() the current activity only

In your current activity,

Intent intent2 = new Intent(ResultActivity.this,
    yourpreviousactivity.class);
    startActivity(intent2);
    finish();

Upvotes: 1

Alexis C.
Alexis C.

Reputation: 93842

Just call finish() in your onClick method

Upvotes: 1

Related Questions