Android 从自定义片段调用DialogFragment,然后设置其属性

Android 从自定义片段调用DialogFragment,然后设置其属性,android,android-fragments,google-play-services,android-dialogfragment,google-plus-signin,Android,Android Fragments,Google Play Services,Android Dialogfragment,Google Plus Signin,在成功地遵循了指南之后,我正在尝试将所有与Google+相关的代码从我的MainActivity移动到一个单独的自定义项 然而,我被卡在了最后一个位置-在我的自定义片段中,我不知道如何在对话框片段被取消后访问mResolvingError字段: public class GoogleFragment extends Fragment implements GoogleApiClient.OnConnectionFailedListener { private boole

在成功地遵循了指南之后,我正在尝试将所有与Google+相关的代码从我的
MainActivity
移动到一个单独的自定义项

然而,我被卡在了最后一个位置-在我的自定义片段中,我不知道如何在
对话框片段
被取消后访问
mResolvingError
字段:

public class GoogleFragment extends Fragment
        implements GoogleApiClient.OnConnectionFailedListener {

    private boolean mResolvingError = false; // HOW TO ACCESS?

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (mResolvingError) {
            // Already attempting to resolve an error.
            return;
        } else if (connectionResult.hasResolution()) {
            try {
                mResolvingError = true;
                connectionResult.startResolutionForResult(getActivity(), REQUEST_RESOLVE_ERROR);
            } catch (IntentSender.SendIntentException e) {
                // There was an error with the resolution intent. Try again.
                if (mGoogleApiClient != null)
                    mGoogleApiClient.connect();
            }
        } else {
            // Show dialog using GoogleApiAvailability.getErrorDialog()
            showErrorDialog(connectionResult.getErrorCode());
            mResolvingError = true;
        }
    }

    private void showErrorDialog(int errorCode) {
        // Create a fragment for the error dialog
        ErrorDialogFragment dialogFragment = new ErrorDialogFragment();
        // Pass the error that should be displayed
        Bundle args = new Bundle();
        args.putInt(ARGS_DIALOG_ERROR, errorCode);
        dialogFragment.setArguments(args);
        dialogFragment.show(getActivity().getSupportFragmentManager(), TAG_DIALOG_ERROR);
    }

    public static class ErrorDialogFragment extends DialogFragment {
        public ErrorDialogFragment() {
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Get the error code and retrieve the appropriate dialog
            int errorCode = this.getArguments().getInt(ARGS_DIALOG_ERROR);
            return GoogleApiAvailability.getInstance().getErrorDialog(
                    this.getActivity(),
                    errorCode,
                    REQUEST_RESOLVE_ERROR);
        }

        @Override
        public void onDismiss(DialogInterface dialog) {
            mResolvingError = false; // DOES NOT COMPILE
        }
    }
}
请问我应该在这里做什么

如果我将
ErrorDialogFragment
设置为非静态,则会出现编译错误:

这个片段内部类应该是静态的 (GoogleFragment.ErrorDialogFragment)

如果我让它保持静态-我也不能访问变量

我正在为我的问题考虑两种解决方法:

  • 使用
    LocalBroadcastManager
    将自定义
    Intent
    ErrorDialogFragment
    发送到
    GoogleFragment
  • GoogleFragment
    中定义一个自定义方法,并通过
    getSupportFragmentManager()访问它。findFragmentByTag()
  • 但有没有更简单的解决办法

    更新:

    public static final int REQUEST_GOOGLE_PLAY_SERVICES = 1972;
    public static final int REQUEST_GOOGLE_PLUS_LOGIN = 2015;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null)
            startRegistrationService();
    }
    
    private void startRegistrationService() {
        GoogleApiAvailability api = GoogleApiAvailability.getInstance();
        int code = api.isGooglePlayServicesAvailable(this);
        if (code == ConnectionResult.SUCCESS) {
            onActivityResult(REQUEST_GOOGLE_PLAY_SERVICES, Activity.RESULT_OK, null);
        } else if (api.isUserResolvableError(code) &&
            api.showErrorDialogFragment(this, code, REQUEST_GOOGLE_PLAY_SERVICES)) {
            // wait for onActivityResult call (see below)
        } else {
            String str = GoogleApiAvailability.getInstance().getErrorString(code);
            Toast.makeText(this, str, Toast.LENGTH_LONG).show();
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode) {
            case REQUEST_GOOGLE_PLAY_SERVICES:
                if (resultCode == Activity.RESULT_OK) {
                    Intent i = new Intent(this, RegistrationService.class); 
                    startService(i); // OK, init GCM
                }
                break;
    
            case REQUEST_GOOGLE_PLUS_LOGIN:
                if (resultCode == Activity.RESULT_OK) {
                    GoogleFragment f = (GoogleFragment) getSupportFragmentManager().
                        findFragmentByTag(GoogleFragment.TAG);
                    if (f != null && f.isVisible())
                        f.onActivityResult(requestCode, resultCode, data);
                }
                break;
    
            default:
                super.onActivityResult(requestCode, resultCode, data);
        }
    }
    
    public class GoogleFragment extends Fragment
            implements View.OnClickListener,
            GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener {
    
        public final static String TAG = "GoogleFragment";
    
        private GoogleApiClient mGoogleApiClient;
    
        private ImageButton mLoginButton;
        private ImageButton mLogoutButton;
    
        public GoogleFragment() {
            // required empty public constructor
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
    
            View v = inflater.inflate(R.layout.fragment_google, container, false);
    
            mGoogleApiClient = new GoogleApiClient.Builder(getContext())
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(Plus.API)
                    .addScope(Plus.SCOPE_PLUS_PROFILE)
                    .build();
    
            mLoginButton = (ImageButton) v.findViewById(R.id.login_button);
            mLoginButton.setOnClickListener(this);
    
            mLogoutButton = (ImageButton) v.findViewById(R.id.logout_button);
            mLogoutButton.setOnClickListener(this);
    
            return v;
        }
    
        private void googleLogin() {
            mGoogleApiClient.connect();
        }
    
        private void googleLogout() {
            if (mGoogleApiClient.isConnecting() || mGoogleApiClient.isConnected())
                mGoogleApiClient.disconnect();
        }
    
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (resultCode == Activity.RESULT_OK)
                mGoogleApiClient.connect();
        }
    
        @Override
        public void onClick(View v) {
            if (v == mLoginButton)
                googleLogin();
            else
                googleLogout();
        }
    
        @Override
        public void onConnected(Bundle bundle) {
            Person me = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
            if (me != null) {
                String id = me.getId();
                Person.Name name = me.getName();
                String given = name.getGivenName();
                String family = name.getFamilyName();
                boolean female = (me.hasGender() && me.getGender() == 1);
    
                String photo = null;
                if (me.hasImage() && me.getImage().hasUrl()) {
                    photo = me.getImage().getUrl();
                    photo = photo.replaceFirst("\\bsz=\\d+\\b", "sz=300");
                }
    
                String city = "Unknown city";
                List<Person.PlacesLived> places = me.getPlacesLived();
                if (places != null) {
                    for (Person.PlacesLived place : places) {
                        city = place.getValue();
                        if (place.isPrimary())
                            break;
                    }
                }
    
                Toast.makeText(getContext(), "Given: " + given + ", Family: " + family + ", Female: " + female + ", City: " + city, Toast.LENGTH_LONG).show();
            }
        }
    
        @Override
        public void onConnectionSuspended(int i) {
            // ignore? don't know what to do here...
        }
    
        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            if (connectionResult.hasResolution()) {
                try {
                    connectionResult.startResolutionForResult(getActivity(), MainActivity.REQUEST_GOOGLE_PLUS_LOGIN);
                } catch (IntentSender.SendIntentException e) {
                    mGoogleApiClient.connect();
                }
            } else {
                int code = connectionResult.getErrorCode();
                String str = GoogleApiAvailability.getInstance().getErrorString(code);
                Toast.MakeText(getContext(), str, Toast.LENGTH_LONG).show();
            }
        }
    }
    
    我已将
    mResolvingError
    字段更改为public,并尝试了以下代码:

        @Override
        public void onDismiss(DialogInterface dialog) {
            GoogleFragment f = (GoogleFragment) getActivity().getSupportFragmentManager().findFragmentByTag(GoogleFragment.TAG);
            if (f != null && f.isVisible()) {
                f.mResolvingError = false;
            }
        }
    
    但是我不知道如何正确地测试它,如果那里需要
    f.isVisible()

    更新2:

    public static final int REQUEST_GOOGLE_PLAY_SERVICES = 1972;
    public static final int REQUEST_GOOGLE_PLUS_LOGIN = 2015;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null)
            startRegistrationService();
    }
    
    private void startRegistrationService() {
        GoogleApiAvailability api = GoogleApiAvailability.getInstance();
        int code = api.isGooglePlayServicesAvailable(this);
        if (code == ConnectionResult.SUCCESS) {
            onActivityResult(REQUEST_GOOGLE_PLAY_SERVICES, Activity.RESULT_OK, null);
        } else if (api.isUserResolvableError(code) &&
            api.showErrorDialogFragment(this, code, REQUEST_GOOGLE_PLAY_SERVICES)) {
            // wait for onActivityResult call (see below)
        } else {
            String str = GoogleApiAvailability.getInstance().getErrorString(code);
            Toast.makeText(this, str, Toast.LENGTH_LONG).show();
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode) {
            case REQUEST_GOOGLE_PLAY_SERVICES:
                if (resultCode == Activity.RESULT_OK) {
                    Intent i = new Intent(this, RegistrationService.class); 
                    startService(i); // OK, init GCM
                }
                break;
    
            case REQUEST_GOOGLE_PLUS_LOGIN:
                if (resultCode == Activity.RESULT_OK) {
                    GoogleFragment f = (GoogleFragment) getSupportFragmentManager().
                        findFragmentByTag(GoogleFragment.TAG);
                    if (f != null && f.isVisible())
                        f.onActivityResult(requestCode, resultCode, data);
                }
                break;
    
            default:
                super.onActivityResult(requestCode, resultCode, data);
        }
    }
    
    public class GoogleFragment extends Fragment
            implements View.OnClickListener,
            GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener {
    
        public final static String TAG = "GoogleFragment";
    
        private GoogleApiClient mGoogleApiClient;
    
        private ImageButton mLoginButton;
        private ImageButton mLogoutButton;
    
        public GoogleFragment() {
            // required empty public constructor
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
    
            View v = inflater.inflate(R.layout.fragment_google, container, false);
    
            mGoogleApiClient = new GoogleApiClient.Builder(getContext())
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(Plus.API)
                    .addScope(Plus.SCOPE_PLUS_PROFILE)
                    .build();
    
            mLoginButton = (ImageButton) v.findViewById(R.id.login_button);
            mLoginButton.setOnClickListener(this);
    
            mLogoutButton = (ImageButton) v.findViewById(R.id.logout_button);
            mLogoutButton.setOnClickListener(this);
    
            return v;
        }
    
        private void googleLogin() {
            mGoogleApiClient.connect();
        }
    
        private void googleLogout() {
            if (mGoogleApiClient.isConnecting() || mGoogleApiClient.isConnected())
                mGoogleApiClient.disconnect();
        }
    
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (resultCode == Activity.RESULT_OK)
                mGoogleApiClient.connect();
        }
    
        @Override
        public void onClick(View v) {
            if (v == mLoginButton)
                googleLogin();
            else
                googleLogout();
        }
    
        @Override
        public void onConnected(Bundle bundle) {
            Person me = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
            if (me != null) {
                String id = me.getId();
                Person.Name name = me.getName();
                String given = name.getGivenName();
                String family = name.getFamilyName();
                boolean female = (me.hasGender() && me.getGender() == 1);
    
                String photo = null;
                if (me.hasImage() && me.getImage().hasUrl()) {
                    photo = me.getImage().getUrl();
                    photo = photo.replaceFirst("\\bsz=\\d+\\b", "sz=300");
                }
    
                String city = "Unknown city";
                List<Person.PlacesLived> places = me.getPlacesLived();
                if (places != null) {
                    for (Person.PlacesLived place : places) {
                        city = place.getValue();
                        if (place.isPrimary())
                            break;
                    }
                }
    
                Toast.makeText(getContext(), "Given: " + given + ", Family: " + family + ", Female: " + female + ", City: " + city, Toast.LENGTH_LONG).show();
            }
        }
    
        @Override
        public void onConnectionSuspended(int i) {
            // ignore? don't know what to do here...
        }
    
        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            if (connectionResult.hasResolution()) {
                try {
                    connectionResult.startResolutionForResult(getActivity(), MainActivity.REQUEST_GOOGLE_PLUS_LOGIN);
                } catch (IntentSender.SendIntentException e) {
                    mGoogleApiClient.connect();
                }
            } else {
                int code = connectionResult.getErrorCode();
                String str = GoogleApiAvailability.getInstance().getErrorString(code);
                Toast.MakeText(getContext(), str, Toast.LENGTH_LONG).show();
            }
        }
    }
    

    也许我应该在我的代码中使用with?

    BladeCoder的评论很有见解,谢谢

    然而,我意识到,保存和恢复
    mResolvingError
    的所有麻烦都是不必要的,因为无论如何都会启动一个单独的活动并阻碍我的应用程序,所以我是否旋转设备并不重要

    这是我启动GCM并获取Google+用户数据的最后代码-

    MainActivity.java:

    public static final int REQUEST_GOOGLE_PLAY_SERVICES = 1972;
    public static final int REQUEST_GOOGLE_PLUS_LOGIN = 2015;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null)
            startRegistrationService();
    }
    
    private void startRegistrationService() {
        GoogleApiAvailability api = GoogleApiAvailability.getInstance();
        int code = api.isGooglePlayServicesAvailable(this);
        if (code == ConnectionResult.SUCCESS) {
            onActivityResult(REQUEST_GOOGLE_PLAY_SERVICES, Activity.RESULT_OK, null);
        } else if (api.isUserResolvableError(code) &&
            api.showErrorDialogFragment(this, code, REQUEST_GOOGLE_PLAY_SERVICES)) {
            // wait for onActivityResult call (see below)
        } else {
            String str = GoogleApiAvailability.getInstance().getErrorString(code);
            Toast.makeText(this, str, Toast.LENGTH_LONG).show();
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode) {
            case REQUEST_GOOGLE_PLAY_SERVICES:
                if (resultCode == Activity.RESULT_OK) {
                    Intent i = new Intent(this, RegistrationService.class); 
                    startService(i); // OK, init GCM
                }
                break;
    
            case REQUEST_GOOGLE_PLUS_LOGIN:
                if (resultCode == Activity.RESULT_OK) {
                    GoogleFragment f = (GoogleFragment) getSupportFragmentManager().
                        findFragmentByTag(GoogleFragment.TAG);
                    if (f != null && f.isVisible())
                        f.onActivityResult(requestCode, resultCode, data);
                }
                break;
    
            default:
                super.onActivityResult(requestCode, resultCode, data);
        }
    }
    
    public class GoogleFragment extends Fragment
            implements View.OnClickListener,
            GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener {
    
        public final static String TAG = "GoogleFragment";
    
        private GoogleApiClient mGoogleApiClient;
    
        private ImageButton mLoginButton;
        private ImageButton mLogoutButton;
    
        public GoogleFragment() {
            // required empty public constructor
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
    
            View v = inflater.inflate(R.layout.fragment_google, container, false);
    
            mGoogleApiClient = new GoogleApiClient.Builder(getContext())
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(Plus.API)
                    .addScope(Plus.SCOPE_PLUS_PROFILE)
                    .build();
    
            mLoginButton = (ImageButton) v.findViewById(R.id.login_button);
            mLoginButton.setOnClickListener(this);
    
            mLogoutButton = (ImageButton) v.findViewById(R.id.logout_button);
            mLogoutButton.setOnClickListener(this);
    
            return v;
        }
    
        private void googleLogin() {
            mGoogleApiClient.connect();
        }
    
        private void googleLogout() {
            if (mGoogleApiClient.isConnecting() || mGoogleApiClient.isConnected())
                mGoogleApiClient.disconnect();
        }
    
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (resultCode == Activity.RESULT_OK)
                mGoogleApiClient.connect();
        }
    
        @Override
        public void onClick(View v) {
            if (v == mLoginButton)
                googleLogin();
            else
                googleLogout();
        }
    
        @Override
        public void onConnected(Bundle bundle) {
            Person me = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
            if (me != null) {
                String id = me.getId();
                Person.Name name = me.getName();
                String given = name.getGivenName();
                String family = name.getFamilyName();
                boolean female = (me.hasGender() && me.getGender() == 1);
    
                String photo = null;
                if (me.hasImage() && me.getImage().hasUrl()) {
                    photo = me.getImage().getUrl();
                    photo = photo.replaceFirst("\\bsz=\\d+\\b", "sz=300");
                }
    
                String city = "Unknown city";
                List<Person.PlacesLived> places = me.getPlacesLived();
                if (places != null) {
                    for (Person.PlacesLived place : places) {
                        city = place.getValue();
                        if (place.isPrimary())
                            break;
                    }
                }
    
                Toast.makeText(getContext(), "Given: " + given + ", Family: " + family + ", Female: " + female + ", City: " + city, Toast.LENGTH_LONG).show();
            }
        }
    
        @Override
        public void onConnectionSuspended(int i) {
            // ignore? don't know what to do here...
        }
    
        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            if (connectionResult.hasResolution()) {
                try {
                    connectionResult.startResolutionForResult(getActivity(), MainActivity.REQUEST_GOOGLE_PLUS_LOGIN);
                } catch (IntentSender.SendIntentException e) {
                    mGoogleApiClient.connect();
                }
            } else {
                int code = connectionResult.getErrorCode();
                String str = GoogleApiAvailability.getInstance().getErrorString(code);
                Toast.MakeText(getContext(), str, Toast.LENGTH_LONG).show();
            }
        }
    }
    
    GoogleFragment.java:

    public static final int REQUEST_GOOGLE_PLAY_SERVICES = 1972;
    public static final int REQUEST_GOOGLE_PLUS_LOGIN = 2015;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null)
            startRegistrationService();
    }
    
    private void startRegistrationService() {
        GoogleApiAvailability api = GoogleApiAvailability.getInstance();
        int code = api.isGooglePlayServicesAvailable(this);
        if (code == ConnectionResult.SUCCESS) {
            onActivityResult(REQUEST_GOOGLE_PLAY_SERVICES, Activity.RESULT_OK, null);
        } else if (api.isUserResolvableError(code) &&
            api.showErrorDialogFragment(this, code, REQUEST_GOOGLE_PLAY_SERVICES)) {
            // wait for onActivityResult call (see below)
        } else {
            String str = GoogleApiAvailability.getInstance().getErrorString(code);
            Toast.makeText(this, str, Toast.LENGTH_LONG).show();
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode) {
            case REQUEST_GOOGLE_PLAY_SERVICES:
                if (resultCode == Activity.RESULT_OK) {
                    Intent i = new Intent(this, RegistrationService.class); 
                    startService(i); // OK, init GCM
                }
                break;
    
            case REQUEST_GOOGLE_PLUS_LOGIN:
                if (resultCode == Activity.RESULT_OK) {
                    GoogleFragment f = (GoogleFragment) getSupportFragmentManager().
                        findFragmentByTag(GoogleFragment.TAG);
                    if (f != null && f.isVisible())
                        f.onActivityResult(requestCode, resultCode, data);
                }
                break;
    
            default:
                super.onActivityResult(requestCode, resultCode, data);
        }
    }
    
    public class GoogleFragment extends Fragment
            implements View.OnClickListener,
            GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener {
    
        public final static String TAG = "GoogleFragment";
    
        private GoogleApiClient mGoogleApiClient;
    
        private ImageButton mLoginButton;
        private ImageButton mLogoutButton;
    
        public GoogleFragment() {
            // required empty public constructor
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
    
            View v = inflater.inflate(R.layout.fragment_google, container, false);
    
            mGoogleApiClient = new GoogleApiClient.Builder(getContext())
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(Plus.API)
                    .addScope(Plus.SCOPE_PLUS_PROFILE)
                    .build();
    
            mLoginButton = (ImageButton) v.findViewById(R.id.login_button);
            mLoginButton.setOnClickListener(this);
    
            mLogoutButton = (ImageButton) v.findViewById(R.id.logout_button);
            mLogoutButton.setOnClickListener(this);
    
            return v;
        }
    
        private void googleLogin() {
            mGoogleApiClient.connect();
        }
    
        private void googleLogout() {
            if (mGoogleApiClient.isConnecting() || mGoogleApiClient.isConnected())
                mGoogleApiClient.disconnect();
        }
    
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (resultCode == Activity.RESULT_OK)
                mGoogleApiClient.connect();
        }
    
        @Override
        public void onClick(View v) {
            if (v == mLoginButton)
                googleLogin();
            else
                googleLogout();
        }
    
        @Override
        public void onConnected(Bundle bundle) {
            Person me = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
            if (me != null) {
                String id = me.getId();
                Person.Name name = me.getName();
                String given = name.getGivenName();
                String family = name.getFamilyName();
                boolean female = (me.hasGender() && me.getGender() == 1);
    
                String photo = null;
                if (me.hasImage() && me.getImage().hasUrl()) {
                    photo = me.getImage().getUrl();
                    photo = photo.replaceFirst("\\bsz=\\d+\\b", "sz=300");
                }
    
                String city = "Unknown city";
                List<Person.PlacesLived> places = me.getPlacesLived();
                if (places != null) {
                    for (Person.PlacesLived place : places) {
                        city = place.getValue();
                        if (place.isPrimary())
                            break;
                    }
                }
    
                Toast.makeText(getContext(), "Given: " + given + ", Family: " + family + ", Female: " + female + ", City: " + city, Toast.LENGTH_LONG).show();
            }
        }
    
        @Override
        public void onConnectionSuspended(int i) {
            // ignore? don't know what to do here...
        }
    
        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            if (connectionResult.hasResolution()) {
                try {
                    connectionResult.startResolutionForResult(getActivity(), MainActivity.REQUEST_GOOGLE_PLUS_LOGIN);
                } catch (IntentSender.SendIntentException e) {
                    mGoogleApiClient.connect();
                }
            } else {
                int code = connectionResult.getErrorCode();
                String str = GoogleApiAvailability.getInstance().getErrorString(code);
                Toast.MakeText(getContext(), str, Toast.LENGTH_LONG).show();
            }
        }
    }
    
    公共类GoogleFragment扩展了片段
    实现View.OnClickListener,
    GoogleAppClient.ConnectionCallbacks,
    GoogleAppClient.OnConnectionFailedListener{
    公共最终静态字符串标记=“GoogleFragment”;
    私人GoogleapClient MGoogleapClient;
    私有图像按钮mLoginButton;
    私有图像按钮mLogoutButton;
    公共谷歌(GoogleFragment){
    //必需的空公共构造函数
    }
    @凌驾
    创建视图上的公共视图(布局、充气机、视图组容器、,
    Bundle savedInstanceState){
    视图v=充气机。充气(R.layout.fragment\u谷歌,容器,假);
    mgoogleapclient=新的Googleapclient.Builder(getContext())
    .addConnectionCallbacks(此)
    .addOnConnectionFailedListener(此)
    .addApi(加上.API)
    .addScope(Plus.SCOPE\u Plus\u配置文件)
    .build();
    mLoginButton=(ImageButton)v.findViewById(R.id.login_按钮);
    mLoginButton.setOnClickListener(这个);
    mLogoutButton=(ImageButton)v.findViewById(R.id.logout_按钮);
    mLogoutButton.setOnClickListener(这个);
    返回v;
    }
    私有void googleLogin(){
    mGoogleApiClient.connect();
    }
    私有void googleLogout(){
    if(mGoogleApiClient.isConnecting()| | mGoogleApiClient.isConnected())
    mGoogleApiClient.disconnect();
    }
    @凌驾
    ActivityResult上的公共void(int请求代码、int结果代码、意图数据){
    if(resultCode==Activity.RESULT\u确定)
    mGoogleApiClient.connect();
    }
    @凌驾
    公共void onClick(视图v){
    if(v==mLoginButton)
    谷歌登录();
    其他的
    谷歌注销();
    }
    @凌驾
    未连接的公共空间(捆绑包){
    Person me=Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
    如果(me!=null){
    字符串id=me.getId();
    Person.Name Name=me.getName();
    字符串given=name.getGivenName();
    String family=name.getFamilyName();
    布尔女性=(me.hasGender()&&me.getGender()==1);
    字符串photo=null;
    if(me.hasImage()&&me.getImage().hasUrl()){
    photo=me.getImage().getUrl();
    photo=photo.replaceFirst(\\bsz=\\d+\\b”,“sz=300”);
    }
    字符串city=“未知城市”;
    List places=me.getPlacesLived();
    if(places!=null){
    用于(Person.PlacesLived place:places){
    city=place.getValue();
    if(place.isPrimary())
    打破
    }
    }
    Toast.makeText(getContext(),“给定:+Given+”,家庭:+Family+,女性:+Female+”,城市:+City,Toast.LENGTH_LONG.show();
    }
    }
    @凌驾
    公共空间连接暂停(int i){
    //忽略?不知道该怎么办。。。
    }
    @凌驾
    公共无效onConnectionFailed(ConnectionResult ConnectionResult){
    if(connectionResult.hasResolution()){
    试一试{
    connectionResult.startResolutionForResult(getActivity(),MainActivity.REQUEST\u GOOGLE\u PLUS\u登录);
    }catch(IntentSender.sendtintentexe){
    mGoogleApiClient.connect();
    }
    }否则{
    int code=connectionResult.getErrorCode();
    String str=GoogleApiAvailability.getInstance().getErrorString(代码);
    Toast.MakeText(getContext(),str,Toast.LENGTH_LONG).show();
    }
    }
    }
    
    您应该用另一种方法:被调用方必须将结果发送回调用方。为此,让调用者实现一个监听器接口,以便被调用者使用它来传递结果。如果调用者是活动,则被调用者片段可以使用
    getActivity()
    检索它。如果调用者是片段,则在创建被调用者时对其使用
    setTargetFragment()
    ,并