在Fragment Android中使用GoogleApiClient

时间:2016-05-22 23:11:45

标签: google-maps fragment android-context google-api-client

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

大多数示例在括号中使用“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();
}

1 个答案:

答案 0 :(得分:8)

这里需要上下文,你可以使用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 {
    ...
}

所以,&#39;这个&#39;这里指的是你的MapFragment类。当你通过这个&#39;在上面的方法中,他们使用他们的回调。

相关问题