Let’s start with my usage scenario:
I wrote an activity that uses the ActionBar.
In this activity, there are fragments. By default, a homeFragment is opened, and clicking on a button will bring you to the detailFragment.
When the detailFragment is started, a problem occurs:
I want the return arrow “<” to appear in the ActionBar when the detailFragment opens.
So I wrote in onStart:
@Override public void onStart() { super.onStart(); ActionBar actionBar = getActivity().getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setIcon( new ColorDrawable(getResources().getColor(android.R.color.transparent))); // In this case, I changed the icon to transparent}Copy the code
There is a back button on the ActionBar, and I want to close my fragment by clicking that button
So I listen for the onOptionsItemSelected event
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
getActivity().getFragmentManager().popBackStack();
return false;
}
return super.onOptionsItemSelected(item);
}
Copy the code
However, after clicking the back button, it will not work. You will notice that onOptionsItemSelected will not be called.
Solution: call setHasOptionsMenu(true) on onCreate;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
Copy the code
Handle the ActionBar icon status of homeFragment
Since I have a homeFragment that will be my main fragment, I want the fragment that overwrites it to control the actionbar (i.e., turn into a return icon), and when the fragment that overwrites it closes, When homeFragment reappears, it should be the same as before (icon, no back button).
To do this, get the actionBar Icon and get its Icon.
The code is as follows:
Copy the code
Drawable actionbar_lastHomeIcon;
@override public void onStart() {Override public void onStart() {super.onstart (); ActionBar actionBar = getActivity().getActionBar(); actionBar.setDisplayHomeAsUpEnabled(false); if (actionbar_lastHomeIcon ! = null) actionBar.setIcon(actionbar_lastHomeIcon); } @override public void onPause() {super.onpause (); ImageView imageView = (ImageView) getActivity().findViewById( android.R.id.home); actionbar_lastHomeIcon = imageView.getDrawable(); }Copy the code
Reference:
Stackoverflow.com/questions/2…