无法将 FloatingActionButton 添加到片段 class 中的 FloatingActionMenu

Cannot add FloatingActionButton to FloatingActionMenu in fragment class

我正在尝试将 FloatingActionButton 添加到 FloatingActionMenu 但是在 FloatingActionButton 初始化期间无法获取上下文 所有方法 return null

这是我的片段调用

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
import demo.com.example.syed.test.R;
public class stdDetails extends android.support.v4.app.Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    FloatingActionMenu detailsfabmenu=(FloatingActionMenu)Container.findViewById(R,id,std_Main_Detials_fab_menu);
    FoatingActionButton(getContext());
    detailsfabmenu.addButton(changename);
    return inflater.inflate(R.layout.stddetailsfragment,container,false);
}}

代码

FloatingActionButton changename=new FloatingActionButton(getContext());

returns 空值 我什至尝试了以下基于 avilabel answers

的选项
FloatingActionButton changename=new FloatingActionButton(container.getContext());

FloatingActionButton changename=new FloatingActionButton(getActivity().getApplicationContext());

FloatingActionButton changename=new FloatingActionButton(this.getContext());

FloatingActionButton changename=new FloatingActionButton(this.getActivity().getApplicationContext());

这是这里提供的所有答案 Using context in a fragment

这是初始化 FAB 的方式:

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fabBtn);

这里fabBtn是布局XML文件中你FAB的id。

更新:

使用这行代码:

FloatingActionButton changename=new FloatingActionButton(getBaseContext());

您应该从 MainActivity 调用浮动操作按钮

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fabBtn);
fab.show().

如果您想为特定片段显示您的 fab,您可以使用片段标签:

Fragment fragmentA = new FragmentA();
getFragmentManager().beginTransaction()
.replace(R.id.MainFrameLayout,fragmentA,"YOUR_TARGET_FRAGMENT_TAG")
.addToBackStack("YOUR_SOURCE_FRAGMENT_TAG").commit(); 

然后检查Mainactivity中是否有你想要的片段:

 if(currentFrag.equals("YOUR_TARGET_FRAGMENT_TAG")){
        fab.show();
    }
    else
        fab.hide();