Android 上下文菜单创建中的 getMenuInflater() 方法未定义问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12424063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getMenuInflater( ) method undefined issue in Android Context Menu creation
提问by intrepidkarthi
I am trying to create a context menu item inside a fragment. But I am facing issue with the getMenuInflater() method. It is undefined. I have imported all the necessary packages. Can anyone point out what I am doing wrong here?
我正在尝试在片段中创建一个上下文菜单项。但是我遇到了 getMenuInflater() 方法的问题。它是未定义的。我已经导入了所有必要的包。谁能指出我在这里做错了什么?
Here is my code:
这是我的代码:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.view.MenuItem;
public class FeaturedFragment extends Fragment {
public FeaturedFragment() {
}
public static final String ARG_SECTION_NUMBER = "section_number";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.featured_fragment,container,false);
registerForContextMenu(view);
return view;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.toggleview_menu, menu);
}
}
here is my menu.xml
这是我的 menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/toggle_view"
android:title="Change to ListView"
android:icon="@drawable/collections_view_as_grid"
android:showAsAction="always" />
<item android:id="@+id/grid_view"
android:title="Grid View"
android:orderInCategory="99"
android:showAsAction="never" />
<item android:id="@+id/list_view"
android:title="List View"
android:orderInCategory="99"
android:showAsAction="never" />
</menu>
回答by waqaslam
Change:
改变:
MenuInflater inflater = getMenuInflater();
To this:
对此:
MenuInflater inflater = getActivity().getMenuInflater();