Android: Call another activity when a button is pressed and close the first activity

Biniam Asnake
Feb 27, 2021

Here is a complete class that shows how another activity is called when a button in the first activity is pressed.

public class FirstActivity extends Activity implements View.OnClickListener {

Button goToSecondActivityButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.first_activity);

((TextView) findViewById(R.id.textRecommendationMessage)).setText("This is the first activity");

goToSecondActivityButton= (Button) findViewById(R.id.button_go_to_second_activity);
goToSecondActivityButton.setOnClickListener(this);
}

@Override
public void onClick(View view) {

goToSecondActivity();
}

private void goToSecondActivity() {

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);
finish();
}
}

--

--