1

I have a MainActivity with an fragment view. In the MainActivity, I load this layout:

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.MainLayout);
}

In the MainLayout, is an Float Action Button with the id "fab"

In my fragment view class, I load the fragment view layout like this:

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

       FragementView = inflater.inflate(R.layout.FragmentViewLayout, container, false);
       FloatingActionButton fab = (FloatingActionButton) FragementView .findViewById(R.id.fab);

       return FragementView;
    }

Now I would like to get in the fragment view class, the fab (find by id) but this will be a null object.

Where is my mistake?

Linh
  • 57,942
  • 23
  • 262
  • 279
Stack108
  • 915
  • 2
  • 14
  • 35

3 Answers3

2

If you need to get the view of activity in fragment use getActivity().

Quoting docs

Specifically, the fragment can access the Activity instance with getActivity() and easily perform tasks such as find a view in the activity layout:

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

https://developer.android.com/guide/components/fragments.html

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
0

Your FloatActionButton is in MainLayout layout not FragmentViewLayout layout.
Therefore, you should retrieve it in your Activity like

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.MainLayout);
  ...
  FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
}
Linh
  • 57,942
  • 23
  • 262
  • 279
0

Include FloatingActionButton in your FragmentViewLayout

FragmentViewLayout.xml

<RelativeLayout 
...

//include FloatingActionButton here
...
/>
Rajan Kali
  • 12,627
  • 3
  • 25
  • 37