Reputation: 77
I have created a fragment with action bar menu, that menu was shown but not working when its clicked.
Here is My Fragment:
public class ComposeFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_compose, container, false);
userName = (TextView) view.findViewById(R.id.user_name);
subjectSpinner = (Spinner) view.findViewById(R.id.subject_spinner);
sendButton = (Button) view.findViewById(R.id.send_btn);
messageEditText = (EditText) view.findViewById(R.id.message);
userName.setText(Ezcation.getInstance().userName);
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.compose_menu, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.e("Menu","Before Switch");
switch (item.getItemId()){
case R.id.sent:
Log.e("Menu","Sent");
if (messageEditText.getText().toString().equals("")){
messageEditText.setError("Please Enter your Message");
}else {
sendMessage(messageEditText.getText().toString());
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.messageActivity = (MessageActivity) context;
SpannableString s = new SpannableString("Compose Message");
s.setSpan(new TypefaceSpan(messageActivity, "Miller-Text.ttf"), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
messageActivity.setTitle(s);
}
}
When menu was clicked even Log.e("Menu","Before Switch"); not working.
My Menu xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/sent"
android:title="Sent"
android:orderInCategory="10"
android:icon="@drawable/sent"
app:showAsAction="ifRoom" />
</menu>
Upvotes: 4
Views: 370
Reputation: 1493
add this in your Activity.
@Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);;
}
Upvotes: 1
Reputation: 12379
For Future visiters you should use this in Activity class:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
To work properly hardcoding false isnt the right way
Upvotes: 7
Reputation: 37404
The super call
is missing inside onCreateOptionsMenu
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.compose_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
Upvotes: 0