There are two activities in my app. I want to perform a simple function. In Second Activity, If button is clicked it should hide and go back to First Activity And If I click the button in First Activity the Second Activity should be open with hidden button. I've achieved this by below code.
But the problem is. I can't close (call onDestroy())the app when I press back button while I'm in First Activity. The back button performs switch between two activities.
First Activity Java:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class first extends AppCompatActivity {
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(first.this, second.class);
startActivity(intent);
}
});
}
public void onBackPressed() {
super.onBackPressed();
}
}
Second Activity Java:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class second extends AppCompatActivity {
Button btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
onBackPressed();
btn2 = (Button) findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
btn2.setVisibility(View.GONE);
Intent intent = new Intent(second.this, first.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
});
}
public void onBackPressed() {
intent = new Intent(second.this, first.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
}
How can I call OnDestroy() in this Condition?
The reason is you override onBackPressed() in the second activity. So that means everytime you press the back button on your second activity, it will create a new first activity instead return to the old one. The app will stuck in this loop. Try to remove onBackPressed method on second activity or call finish() in it.