简体   繁体   中英

Cannot add FloatingActionButton to FloatingActionMenu in fragment class

I am trying to add FloatingActionButton to FloatingActionMenu but when during initilization of FloatingActionButton cannot get context all methods return null

this is my fragment calls

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);
}}

code

FloatingActionButton changename=new FloatingActionButton(getContext());

returns null value i have even tried following options based on 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());

this are all answer's provided here Using context in a fragment

This is how you initialize a FAB:

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

Here fabBtn is the id of your FAB in the layout XML file.

Update:

Use this line of code:

FloatingActionButton changename=new FloatingActionButton(getBaseContext());

You should call your Floating Action Button from MainActivity

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

If you want to show your fab for a specific fragment you can use fragment tag:

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

And then check if you have the desired fragment in Mainactivity:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM