Wednesday, April 23, 2014

Android: How to call another activity when a button is pressed and close the first activity

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();
    }
}

No comments:

Post a Comment