2012-09-14 60 views
18

我想創建一個片段內的上下文菜單項。但是我面臨着getMenuInflater()方法的問題。它是未定義的。我已經導入了所有必需的軟件包。任何人都可以指出我在這裏做錯了嗎?getMenuInflater()方法undefined問題在Android上下文菜單創建

這裏是我的代碼:

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

這裏是我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> 

回答

43

變化:

MenuInflater inflater = getMenuInflater(); 

要這樣:

MenuInflater inflater = getActivity().getMenuInflater(); 
+0

謝謝。有用。但是我的菜單項沒有顯示在視圖中。我用菜單XML文件編輯了我的文章。 – intrepidkarthi

+0

是不是應該在'Activity'的'onCreateOptionsMenu'內使用'getMenuInflator()'? – waqaslam

+0

開發人員指南(http://developer.android.com/guide/topics/ui/menus.html#FloatingContextMenu)表示我們可以將它放在活動或片段中。 – intrepidkarthi