I have an android.support.v4.app.Fragment
in an AppCompatActivity
.
I added a custom Menu in my fragment. Everything works as expected in Android 5 and 6. But if I try this on Android 4, although I can see the toolbar, when I tap the menu items nothing happens and it does not trigger onOptionsItemSelected
This is my fragment:
public class ProfileDetailFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.profile_detail_fragment, container, false);
Toolbar toolbar = (Toolbar) v.findViewById(R.id.toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
return v;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_profile, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
getActivity().onBackPressed();
return true;
case R.id.tick:
save();
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
public void save(){
Toast.makeText(getContext(), "test", Toast.LENGTH_LONG).show();
}
}
This is my fragment layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/fragment_master"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:clickable="true">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
</RelativeLayout>
And this is my menu:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/tick"
android:title="OK"
app:showAsAction="always"
tools:ignore="AppCompatResource" />
</menu>