The action bar home-up button is on the extreme left of the Action bar. Its functionality is to navigate the app to the parent activity. Two ways can achieve the functionality:
Method 1: By adding it to the Android Manifest (AndroidManifest.xml) file.
1 |
android:parentActivityName="<YOUR_PACKAGE>.<PARENT_ACTIVITY_NAME>" |
Add the tag in the activity’s <activity> tag of the Android Manifest file. For example, I have two activities, activity1 and activity2 and I want to go to activity1 on click of activity2’s home up button then my Android Manifest file will be like
1 2 3 4 5 6 7 8 |
<activity android:name=".activity1" </activity> <activity android:name=".activity2" android:parentActivityName="com.example.myapp.activity1" > </activity> |
Method 2: By adding a check in the onOptionsItemSelected() method of the activity.
You can also implement a check on the Home up button ID in the onOptionsItemSelected() method as
1 2 3 4 5 6 7 8 9 10 11 |
@Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if(id == android.R.id.home) { startActivity(new Intent(activity2.this,activity1.class); return true; } return super.onOptionsItemSelected(item); } |
Both methods work well but if you want to give the home-up button the functionality of a back press then go for the second method else you can use whatever suits you.
Official Action Bar documentation -> https://developer.android.com/reference/android/app/ActionBar
Hope this blog helps you understand and gain better navigation control and alternatives to the normal back button press in your Android application.
For more blogs related to Android action bar, please visit –> https://mobikul.com/?s=action+bar
This is Aaastha, signing off.
Keep coding and Keep sharing 🙂
More blogs from me –> https://mobikul.com/author/aastha-gupta371/