Michal
Michal

Reputation: 2084

Why Fragment cannot be public static class?

I came across such problem: I wanted to have some Fragment as public static member of my Activity class.

But when I put such Fragment to layout file I receive such exception:

Caused by: android.support.v4.app.Fragment$InstantiationException: 
Unable to instantiate fragment com.tst.MainActivity.InnerFragment:
make sure class name exists, is public, 
and has an empty constructor that is public
...

My code looks like this:

package com.tst;

public final class MainActivity extends SherlockFragmentActivity {

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

    public static class InnerFragment extends SherlockFragment {

        public InnerFragment() {
            super();
        }
        ...
    }
}

Layout file looks like this:

<LinearLayout
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="vertical" >

  <fragment
        android:id="@+id/inner_fragment"
        android:name="com.tst.MainActivity.InnerFragment"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</LinearLayout>

Now my question is why such code throws this Exception? As Android should be able to instanitate InnerFragment as it is public static. What is more I used to use public static Fragments and they worked, but on that time I added them programmatically in code not in xml definition.

Regards, Michal

Upvotes: 1

Views: 1772

Answers (1)

Alex Lockwood
Alex Lockwood

Reputation: 83311

Change

android:name="com.tst.MainActivity.InnerFragment"

to

android:class="com.tst.MainActivity$InnerFragment"

Upvotes: 4

Related Questions