
上QQ阅读APP看书,第一时间看更新
How to do it...
- Since the Android Studio New Project wizard has already created the first activity, we just need to create the second activity. Open the ActivitySwitcher project and navigate to File | New | Activity | Empty Activity, as shown in this screenshot:

- In the New Android Activity dialog, you can leave the default Activity Name as is, or change it to SecondActivity, as follows:

- Open the MainActivity.java file and add the following function:
public void onClickSwitchActivity(View view) { Intent intent = new Intent(this, SecondActivity.class); startActivity(intent); }
- Now, open the activity_main.xml file located in the res/layout folder and replace the <TextView /> with the following XML to create the button:
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:text="Launch Second Activity"
android:onClick="onClickSwitchActivity"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
- You can run the code at this point and see the second activity open. We're going to go further and add a button to SecondActivity to close it, which will bring us back to the first activity. Open the SecondActivity.java file and
add this function:
public void onClickClose(View view) { finish(); }
- Finally, add the Close button to the SecondActivity layout. Open the activity_second.xml file and add the following <Button> element to the auto-generated ConstraintLayout:
<Button
android:id="@+id/buttonClose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="onClickClose"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
- Run the application on your device or emulator and see the buttons in action.