2015-06-15 20 views
7

Próbuję nadmuchać menu w klasie, która dziedziczy klasę Fragment. Oto moja OnCreateOptionsMenu() metoda -android getMenuInflater() w podklasie fragmentu - nie można rozwiązać metody

@Override 
public boolean OnCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.forecastfragment, menu) ; 
    return true; 
} 

Pojawia się następujący błąd:

Cannot resolve method 'getMenuInflater()'

ja próbowałem:

MenuInflater inflater = getActivity().getMenuInflater(); 

ale potem Android Studio podkreśla @Override na czerwono i stwierdza:

Method does not override method from its superclass

Próbowałem też stworzyć getMenuInflater metody w tej samej klasie i nie powróci new MenuInflater(this)

public MenuInflater getMenuInflater() { 
    return new MenuInflater(this); 
} 

ale wtedy następujący błąd jest generowany:

error: incompatible types: ForecastFragment cannot be converted to Context

error: method does not override or implement a method from a supertype

co mam zrobić?

Odpowiedz

7

Podpis swojej onCreateOptionsMenu nie wygląda dobrze. Spójrz na docs here

spojrzeć ten kod

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setHasOptionsMenu(true);//Make sure you have this line of code. 
} 

@Override 
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 
    // TODO Add your menu entries here 
    super.onCreateOptionsMenu(menu, inflater); 
} 
+1

Chociaż metoda rozwiązuje poprawnie, nadal nie może uzyskać 'metoda nie zastąpi z supertype' odejść. –

0

użyć tego kodu:

@Override 
public boolean OnCreateOptionsMenu(Menu menu, MenuInflater inflater) { 
    inflater.inflate(R.menu.forecastfragment, menu) ; 
    final MenuItem item = menu.findItem(R.id.forecastID); 
} 

gdzie forecastID jest identyfikator elementu w forcastfragment.xml menu. Dodaj także setHasOptionsMenu(true); do swojego OnCreateView(), aby fragment wywoływał metodę.

Jako standardową praktyką jest umieszczanie słowa "menu" w nazwach plików menu, takich jak "forecastfragment_menu.xml". Pozwala uniknąć zamieszania.

1
  • Według API nie overriding się sposób super.
  • Nie wywołujesz poprawnej metody inflate.

Musisz użyć go w ten sposób:

@Override 
public boolean OnCreateOptionsMenu(Menu menu, MenuInflater inflater) { 
    inflater.inflate(R.menu.forecastfragment, menu); 
    return true; 
} 
Powiązane problemy