简体   繁体   中英

Android Facebook setFragment with a regular Fragment

Because setFragment of Facebook is working only with support.fragment, I did the following in order to overcome this when working with regular fragment:

public class NativeFragmentWrapper extends android.support.v4.app.Fragment {
    private final Fragment nativeFragment;

    public NativeFragmentWrapper(Fragment nativeFragment) {
        this.nativeFragment = nativeFragment;
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        nativeFragment.startActivityForResult(intent, requestCode);
    }

    @Override
    public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        nativeFragment.onActivityResult(requestCode, resultCode, data);
    }
}

and in the login page where facebook button resides, I did the following:

authButton.setFragment(new new NativeFragmentWrapper(this));

in Eclipse it worked great but Android Studio 1.0.2 is complaining:

This fragment should provide a default constructor (a public constructor with no arguments). From the Fragment documentation: Every fragment must have an empty constructor, so it can be instantiated when restoring its activity's state. It is strongly recommended that subclasses do not have other constructors with parameters, since these constructors will not be called when the fragment is re-instantiated; instead, arguments can be supplied by the caller with setArguments(Bundle) and later retrieved by the Fragment with getArguments().

So I tried this:

NativeFragmentWrapper f = new NativeFragmentWrapper();
Bundle bundle = new Bundle();
f.setArguments(bundle);
authButton.setFragment(f);

but I didn't find a way to put "this" (which is a Fragment) inside the bundle in order to retrieve it in the wrapper constructor.

I can @SuppressLint("ValidFragment") but I'm sure there is a cleaner way to do it.

The best way is to just use the Fragment class from the v4 support libraries in your app, the signatures are the same, and you just need to change the import statements.

Failing that, the solution in the other post can potentially work (haven't tried it myself), and to solve your problem, just have 2 constructors (one the default, and another that takes a Fragment parameter), and just use the right constructor (ie not the default) when you create the wrapper object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM