Thursday, February 11, 2016

RecyclerView: Some trick with Fragment which was instantiated inside XML

Case:
Fragment inside xml.
Use of view is to use with RecyclerView viewholder.
Sometimes strange RuntimeException occurs: android.content.res.Resources$NotFoundException: Unable to find resource ID ...
XML looks like this:

...

 <someviewgroup android:layout_height="wrap_content" android:layout_width="wrap_content">

  <fragment android:id="+@id/someId" android:layout_height="100dp" android:layout_width="100dp" android:name="bla.bla.YourFragment">

 </fragment></someviewgroup>

...

If you inflate this XML you can face with android.content.res.Resources$NotFoundException.

And stacktrace guides to nowhere:

E/AndroidRuntime(1013): FATAL EXCEPTION: main
E/AndroidRuntime(1013): android.content.res.Resources$NotFoundException: Unable to find resource ID #0xffffffff
E/AndroidRuntime(1013):     at android.content.res.Resources.getResourceName(Resources.java:1659)
E/AndroidRuntime(1013):     at android.support.v4.app.FragmentManagerImpl ......  and etc.

The only way (I could find) to fix crash is to remove id.

But how to get access to instance of Fragment bla.bla.YourFragment from ViewHolder?
You cannot find fragment by id or tag.

Solution is:

In your fragment add callback as tag to rootview:

 public void onViewCreated(View view, Bundle savedInstanceState) {
  view .setTag(new SomeHandler() {
    @Override
    public void someMethod() {
     //Some code
    }
    });
  }

In ViewHolder find that View and get tag (there is no need to explain how to do it).
Voila, you can pass almost any data into your Fragment!


No comments:

Post a Comment