Search code examples
androidfacebook-android-sdk

LoginButton with native Fragment


I'm trying to implement the Facebook LoginButton using the tutorial here https://developers.facebook.com/docs/android/login-with-facebook/v2.0#step2

The problem is on the line authButton.setFragment(this);.

I'm using native fragments (android.app.Fragment) but setFragment expects a support Fragment (android.support.v4.app.Fragment).

EDIT: I cannot switch to support Fragments, I have a big app that uses native Fragments.


Solution

  • I think the solution you are looking for is the wrapper class below. Using this you can just call

    authButton.setFragment(new NativeFragmentWrapper(this));
    

    The wrapper is a support fragment and just passes the method calls from the facebook LoginButton to the native fragment. I'm using this and it works fine.

    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);
        }
    }