调用onOptionsItemSelected

调用onOptionsItemSelected

我试图在按下Dialog Fragment的元素之一时打开弹出菜单,但是即使按下菜单项之一,也永远不会调用onOptionsItemSelected方法。我该怎么解决?

java - 在PopupMenu中不调用onOptionsItemSelected-LMLPHP java - 在PopupMenu中不调用onOptionsItemSelected-LMLPHP

public class AddSongDialogFragment extends DialogFragment implements View.OnClickListener {

private TextView genreTextview;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.addsong_layout, container);
    //...
    genreTextview = (TextView) view.findViewById(R.id.genreTextView);
    view.findViewById(R.id.ll_genre_menu).setOnClickListener(this);
    genreTextview.setText(R.string.press_to_choose_genre);
    return view;
}

//...

public void onClick(View v){
    switch(v.getId()) {
        case R.id.button2:
            dismiss();
            mListener.onChoose();
            break;
        case R.id.ll_genre_menu:
            PopupMenu popup = new PopupMenu(getContext(), v);
            MenuInflater inflater = popup.getMenuInflater();
            inflater.inflate(R.menu.song_genres, popup.getMenu());
            popup.show();
            break;
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    genreTextview.setText(item.getTitle());
    Log.d("songo", "item selected");
    return true;
}


song_genres.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/pop"
        android:title="@string/pop"/>
    <item android:id="@+id/rock"
        android:title="@string/rock" />
    ...
</menu>

最佳答案

您应将setOnMenuItemClickListener(PopupMenu.OnMenuItemClickListener listener)设置为popup

就像下面

popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Log.d("songo", "item selected");
                return false;
            }
        });

10-01 18:48