在 Fragment Android 中使用 GoogleApiClient

Using GoogleApiClient in Fragment Android

我试图将 Google 地图加载到片段中。我不知道这三行应该是什么...(三行注释"problem!")。

大多数示例都在括号中使用 "this"。我知道这是一个片段,而不是 activity,所以我改用了 "getActivity()"。但是,如果我将所有三行都更改为 getActivity(),它也不起作用。请帮忙!提前致谢!

public class MapFragment extends Fragment implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,com.google.android.gms.location.LocationListener {
private static final String TAG = "***MapFragment***";
private final int PERMISSION_CODE = 1;
private GoogleApiClient myGoogleApiClient;
private GoogleMap myMap;
private Location curLocation;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_target, container, false);

// create api client
if (myGoogleApiClient == null) {
    myGoogleApiClient = new GoogleApiClient.Builder(getActivity())  // problem!
            .addConnectionCallbacks(this)   // problem!
            .addOnConnectionFailedListener(this)  // problem!
            .addApi(LocationServices.API)
            .build();
}

这里需要上下文,你可以使用getActivity()

new GoogleApiClient.Builder(getActivity())  // problem!

以下两个方法需要回调,因此您的片段必须实现 ConnectionCallbacks、OnConnectionFailedListener 侦听器。

.addConnectionCallbacks(this)   // problem!
.addOnConnectionFailedListener(this)  // problem!

说明

  • .addConnectionCallbacks 方法需要 ConnectionCallbacks
  • .addOnConnectionFailedListener 方法需要 OnConnectionFailedListener

您已经实现了它们

public class MapFragment extends Fragment implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
    ...
}

因此,'this' 这里 指的是您的 MapFragment class。当您在上述方法中传递 'this' 时,它们会使用它们的回调。