如何在动作栏上使用按钮使用碎片?

时间:2015-10-25 11:52:03

标签: android button android-fragments android-actionbar

我想在片段的操作栏上添加按钮。但是我在下面给出的代码上收到错误。

这是我的片段代码,我想在此标签的操作栏上添加按钮

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
         final View view = inflater.inflate(R.layout.credit_main, container, false);
return view;
    }
@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();

        inflater.inflate(R.menu.search_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            // action with ID action_refresh was selected
            case R.id.search:
                Toast.makeText(getActivity(), "Refresh selected", Toast.LENGTH_SHORT)
                        .show();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

}

此处错误getMenuInflater();无法解决

2 个答案:

答案 0 :(得分:5)

步骤1:制作要添加的xml菜单。

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" >

    <item
        android:id="@+id/item1"
        android:title="@string/filter"
        android:orderInCategory="10"
        android:icon="@drawable/ic_launcher"
        app:showAsAction="ifRoom" />
</menu>

第2步:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

第3步:

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.search_result, menu);
    }

第4步:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.item1){
            //What you want(Code Here) 
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

答案 1 :(得分:1)

您必须致电setHasOptionsMenu(true)才能使其正常运作。

做类似的事情:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

然后将onCreateOptionsMenu()方法与inflater一起使用。

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

查看setHasOptionsMenu()onCreateOptionsMenu()