Start another activity from one activity

  • 1. Create a new android project with two activities ActivityA and ActivityB and corresponding xml layouts activity_a.xml and activity_b.xml
  • 2. Add a button to the first activity’s layout
  • 3.Perform the action of loading ActivityB on button click

There are two ways we can add an action to a button in android
a. Assign a method to the button in the xml layout using the android:onClick attribute.
b. Set an OnClickListener to the button in the activity’s code.

1. Create a new android project in android studio.
In android studio go to File->New->New Project . Learn more
2. Add a button to the first activity’s layout.

Now activity_a.xml code looks like:


And our activity_b.xml is below:

3. Perform the action of loading ActivityB on button click

Method a.Assign a method to the button in the xml layout using the android:onClick attribute:
Add android:onClick=”loadActivityB” to the Button element of activity_a.xml, now the Button element looks like
Here the value of the android:onClick attribute should be the name of the method that actually loads ActivityB. I have create the method named loadActivityB in ActivityA as show below:

This method must be a public method and must accept a View as the only parameter.
The complete ActivityA :

Method b.Set an onClickListener to the button in activity’s code:
Add android:id=”button_load_b” to the Button element of activity_a.xml,
The android:onClick attribute is no more required. Now the Button element looks like
Now we have to access this Button from the ActivityA code and add the action to it.
The complete ActivityA :

Leave a Reply

Your email address will not be published. Required fields are marked *