android片段动作栏菜单

时间:2016-08-31 05:00:46

标签: android android-fragments android-fragmentactivity

我创建了一个带有操作栏菜单的片段,该菜单已显示但单击时无效。

这是我的片段:

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(“菜单”,“切换前”); 也无效。

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

3 个答案:

答案 0 :(得分:5)

对于Future visiters,您应该在Activity类中使用它:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return super.onOptionsItemSelected(item);
}

正常工作硬编码错误不是正确的方法

答案 1 :(得分:1)

在您的活动中添加此内容。

/(ftp|http|https){1}:\/\/(?:.(?! ))+$/

答案 2 :(得分:0)

super call

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