这些是错误:
The method getMenuInflater() is undefined for the type HomeFragment
-Line 27
The method onCreateOptionsMenu(Menu) of type HomeFragment must override or implement a supertype method
-Line 29
The method onCreateOptionsMenu(Menu) of type HomeFragment must override or implement a supertype method
-Line 25
所有这些都在我的HomeFragment.java
package com.colourity.snatsh;
import com.colourity.snatsh.R;
import java.util.ArrayList;
import com.colourity.snatsh.adapter.NavDrawerListAdapter;
import com.colourity.snatsh.model.NavDrawerItem;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
public class HomeFragment extends Fragment {
public HomeFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
}
当我尝试在HomeFragment
而不是MainActivity
上设置操作栏图标时会发生这种情况。我是新人,所以请放轻松。任何帮助都会很棒。解决方案会很好。
修改
我的更新代码:
package com.colourity.snatsh;
import com.colourity.snatsh.R;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
public class HomeFragment extends Fragment {
public HomeFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
@Override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
// Inflate the menu items for use in the action bar
MenuInflater inflater1 = getMenuInflater();
inflater1.inflate(R.menu.main, menu);
return;
}
private MenuInflater getMenuInflater() {
// TODO Auto-generated method stub
return null;
}
}
答案 0 :(得分:3)
简答:片段不能有操作栏,只有活动可以。
更长的答案:Fragment
类不包含您尝试使用或覆盖的任何方法。这些是Activity
类的所有方法。有关每个课程中可用方法的更多信息,我强烈建议您熟悉the Android developer guides。特别是,您可以使用Activity
和Fragment
的文档来了解每个类中的方法。
长答案:片段可以将菜单项添加到由ActionBar
维护的Activity
。为此,您必须覆盖onCreateOptionsMenu (Menu menu, MenuInflater inflater)
。请注意此签名与Activity
的{{3}}的区别。