Emi*_*ile -2 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();
}
Run Code Online (Sandbox Code Playgroud)
这里需要上下文,你可以使用getActivity()
new GoogleApiClient.Builder(getActivity()) // problem!
Run Code Online (Sandbox Code Playgroud)
下面两个方法需要回调,所以你的片段必须实现ConnectionCallbacks,OnConnectionFailedListener监听器.
.addConnectionCallbacks(this) // problem!
.addOnConnectionFailedListener(this) // problem!
Run Code Online (Sandbox Code Playgroud)
说明
你已经实现了它们
public class MapFragment extends Fragment implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
...
}
Run Code Online (Sandbox Code Playgroud)
所以,'this'在这里指的是你的MapFragment类.当你在上面的方法中传递'this'时,他们会使用他们的回调.