开发者

Android compatibility package Fragment as inner static class

I've been using the Android compatibility Package but i encountered the following issue, it seems that whenever i create a Fragment as an inner static class on my application and try to start that activity the it display the following error

android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment org.wr.CreditCardHolderActivity.CreditCardHolderFragment: make sure class name exists, is public, and has an em开发者_Go百科pty constructor that is public

And when i separate the fragment and the activity everything work smoothly, anyone know why? and how can i fix it?

Thanks!


If you have an inner class Fragment like:

public class SomethingFragment extends Fragment {    
  public static final class TypeFragment extends BaseFragment
  {

    public static Fragment newInstance()
    {
        return new TypeFragment();
    }

    private View mRootView;
    private ListView mListView;

    /**
     * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater,
     *      android.view.ViewGroup, android.os.Bundle)
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState)
    {
        mRootView = inflater.inflate(R.layout.fragment_category_list, container, false);
        mListView = (ListView) mRootView.findViewById(R.id.fragment_listview);
        return mRootView;
    }
  }
}

Make sure your qualifier is public when the FragmentActivity tries to reinitiate the fragment it doesn't call it from the concrete class it will handle it from the abstract FragmentActivity, and if your inner class Fragment is private the Activity has no reference to onSaveState, onRestoreState, initialise etc..

private to public fixed it for me!

Update:

Have a look at https://android.googlesource.com/platform/frameworks/support/+/refs/heads/master/v4/java/android/support/v4/app/Fragment.java

The instantiate method calls newInstance() when trying to restore the Fragment from a saved state (where the fragment was completely destroyed).

The newInstance method requires the class to be publicly accessible, so when defined as an inner class this means it has to be public and static where appropriate.

Hope this clears up some future questions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜