如何在片段上显示操作栏图标?

时间:2014-02-23 00:41:23

标签: java android xml android-fragments

我正在为我的应用程序使用导航抽屉,其中包含碎片。我也在使用动作图标。但是当我使用抽屉来改变活动时,动作图标就会出现在所有活动上。我只希望它在其中一个片段上。这是我的代码

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中尝试时,它似乎不起作用。 Here是我正在使用的指南。

修改

我在HomeFragment

中尝试使用指南时遇到以下错误

The method onCreateOptionsMenu(Menu, MenuInflater) in the type Fragment is not applicable for the arguments (Menu) HomeFragment.java /Snatsh/src/com/colourity/snatsh line 29 Java Problem

The method getMenuInflater() is undefined for the type HomeFragment HomeFragment.java /Snatsh/src/com/colourity/snatsh line 27 Java Problem

The method onCreateOptionsMenu(Menu) of type HomeFragment must override or implement a supertype method HomeFragment.java /Snatsh/src/com/colourity/snatsh line 25 Java Problem

1 个答案:

答案 0 :(得分:1)

您的onCreateOptionsMenu缺少参数,请改为尝试:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    // Inflate the menu items for use in the action bar
    inflater.inflate(R.menu.main, menu);
}

并添加额外的导入(如果没有自动完成):

import android.view.MenuInflater;