I have an AppCompatActivity with an ActionBar incorporating a back button. I am starting a inner Fragment class which opens a View on top of the Activity view. The hardware back button closes the Fragment and the Activity view is visible. If however I press the back button on the ActionBar whilst in the Fragment view, the app goes back to MainActivity, the Activities parent. I want to either hide the ActionBar, or ideally give it the same behaviour as the hardware button, as this is obviously annoying behaviour for the user. I have tried creating an instance of the ActionBar in my Activity, like this
ActionBar actionBar = getActionBar();
actionBar.setHomeAsUpEnabled(true);
This gives me a NullPointerException
in runtime. I have searched and am stumped.
Also tried this, where mFragmentManager has .addToBackStack() before it begins the transaction with my Fragment class.
@Override
public void onBackPressed() {
int count = mFragmentManager.getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
//additional code
} else {
mFragmentManager.popBackStack();
}
Log.i(LOG_TAG, "onBackPressed. Count = " + count);
}
~No errors but the ActionBar back button behaviour is no changed. No Log message is recorded~
My mistake, this method did change behaviour but for the hardware back button. It caused a NullPointerException
when trying to getBackStackCount()
on mFragmentManager
.
The action bar "back" button is actually the Up button, and according to Google it is supposed to behave differently from the hardware back button: https://developer.android.com/training/design-navigation/ancestral-temporal.html
That being said, you can intercept touches on this button and do whatever you want with them.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
// your code here
}
return super.onOptionsItemSelected(item);
}
尝试改用getSupportActionBar()
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.