android 片段操作栏菜单

android fragment action bar menu

我创建了一个带有操作栏菜单的片段,该菜单显示但在单击时不起作用。

这是我的片段:

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);
    }
}

即使单击菜单 Log.e("Menu","Before Switch"); 也不起作用。

我的菜单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>

super call 里面缺少 onCreateOptionsMenu

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.compose_menu, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

将此添加到您的 Activity。

@Override public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {
    case android.R.id.home:
        finish();
        break;
}
return super.onOptionsItemSelected(item);;
}

对于未来的访问者,您应该在 Activity class:

中使用它
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return super.onOptionsItemSelected(item);
}

要正常工作硬编码 false 不是正确的方法