Google maps 在Android中使用GoogleAppClient

Google maps 在Android中使用GoogleAppClient,google-maps,fragment,android-context,google-api-client,Google Maps,Fragment,Android Context,Google Api Client,我试图将谷歌地图加载到一个片段中。我不知道这三行应该是什么。。。(三行注释为“问题!”) 大多数示例都在括号中使用“this”。我知道这是一个片段,不是一个活动,所以我使用了“getActivity()”。但是,如果我将所有三行都更改为getActivity(),它也不起作用。请帮忙!提前谢谢 public class MapFragment extends Fragment implements OnMapReadyCallback,GoogleApiClient.ConnectionCall

我试图将谷歌地图加载到一个片段中。我不知道这三行应该是什么。。。(三行注释为“问题!”)

大多数示例都在括号中使用“this”。我知道这是一个片段,不是一个活动,所以我使用了“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()

下面两个方法需要回调,所以您的片段必须实现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类。当您在上述方法中传递“this”时,它们将使用回调

您可以使用getActivity(),并且您试图在返回后构建它?@Blackkara如果我在第二行使用getActivity(),它会给出一个错误,显示“生成器中的addConnectionCallbacks(com.google.android.gms.common.api.GoogleAppClient.ConnectionCallbacks)无法应用于(android.support.v4.app.FragmentActivity)”在返回之前执行返回之前执行返回之前执行没有任何区别…您给出了什么错误?我想我已经实现了这两个接口?这很有效!非常感谢。你能解释一下“这个”代表什么吗?
public class MapFragment extends Fragment implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
    ...
}