FragmentActivity无法转换为ConnectionCallbacks

时间:2017-03-09 04:03:29

标签: android

因此,我正在尝试将Google地图视图实施为片段,然后在其上显示用户的当前位置。因为我正在处理Fragment而不是活动,所以我在使用Context变量方面遇到了一些麻烦。我正在使用 getActivity()和container.getContext()而不是 this ,以便让它使用Fragment并且除了一个之外它没有给我任何错误地点。这是我的方法,我只是粘贴在相关的方法中:

public class MainFragment extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment by using global mView
        mView = inflater.inflate(R.layout.fragment_main, container, false);
        fragment_context = container.getContext();
        return mView;
    }


protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                .addConnectionCallbacks(getActivity()) //ERROR
                .addOnConnectionFailedListener(getActivity())
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

}

我在调用addConnectionCallbacks()时遇到错误,告诉我:

Error:(112, 52) error: incompatible types: FragmentActivity cannot be converted to ConnectionCallbacks

如果您想查看完整的源代码,可以查看here。我做错了什么?

1 个答案:

答案 0 :(得分:1)

我无法看到您的FragmentActivity,但我猜它没有implements ConnectionCallbacks。如果是的话,你只需要施展它

    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .addConnectionCallbacks((ConnectionCallbacks)getActivity()) //ERROR
            .addOnConnectionFailedListener(ConnectionCallbacks)getActivity())
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();