0

I have this problem where the fragment.getView() always returns null when called inside another activity despite the fact the the onCreateView method was overriden in side the fragment.

For example: In my activity:

frag = new NewBooksFrag();

In my fragment:

    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View view = null;

    view = inflater.inflate(R.layout.new_book_frag, container,true);

    return view;
}

but when i call

frag.getView()

it stills returns null. Any idea why is this happening? Because in the android documentation, it clearly states getView():

"Get the root view for the fragment's layout (the one returned by onCreateView(LayoutInflater, ViewGroup, Bundle)), if provided."

if this returns null, how can we reference to the view of the fragment?

Thanks in advance

Quinn Wei
  • 2,183
  • 3
  • 14
  • 12

2 Answers2

0

If you didn't miss to post part of code

frag = new NewBooksFrag();

wont call onCreateView() you should attach the fragment to the activity. Use FragmentManager to do that.

Viswanath Lekshmanan
  • 9,945
  • 1
  • 40
  • 64
0

As mentioned by Visamanath you dont add your fragment to activity, you just create it.

To add fragment to activity you can do it by implement it as a View in xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <fragment android:name="com.example.android.fragments.NewBooksFrag"
              android:id="@+id/new_books_fragment"
              android:layout_width="match_parent"
              android:layout_height="match_parent" />

</LinearLayout>

Or by adding this dynamically in the code:

        NewBooksFrag frag = new NewBooksFrag();

        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, frag ).commit();

For more deatils please visit official guide