我在片段像这样:
public class MyFrag extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
@Override View onCreateView(..){
...
Button button = (Button) view.findViewById(R.id.button_layout);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (MyGoogleClass.checkPlayServices(getContext(), getActivity())) {
//here my problem
MyGoogleClass.buildGoogleApiClient(getContext());
}
}
});
}
}
以下我有功能:
@Override
public void onConnected(Bundle arg0) { //do something }
@Override
public void onConnectionSuspended(int i) { //do some else}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) { // log error }
MyGoogleClass 有一个功能:
public static synchronized void buildGoogleApiClient(Context context) {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) context)
.addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) context)
.addApi(LocationServices.API).build();
}
但我的问题是,当我尝试调用函数时,使用“getContext()”会返回错误:
MyActivity无法转换为 com.google.android.gms.common.api.GoogleApiClient $ ConnectionCallbacks
我尝试过:
...
MyGoogleClass.buildGoogleApiClient(this);
...
但我无法编译我的代码,因为它返回:
错误:不兼容的类型:MyFrag无法转换为Context
问题是getContext被引用到 MyActivity ,但是如何在Fragment中创建new GoogleApiClient.Builder(context)
?
答案 0 :(得分:0)
在buildGoogleApiClient()
方法中,您尝试将传递的活动转换为GoogleApiClient.ConnectionCallbacks
addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks)context)
这本身是不可能的。根据文档,这是一个接口,并且由于您的方法中的Activity / Context对象是必需的,您必须将其实现到MyActivity
而不是您的片段中。
public static synchronized void buildGoogleApiClient(
GoogleApiClient.ConnectionCallbacks conCallbacks,
GoogleApiClient.OnConnectionFailedListener conListener)
throws IllegalArgumentException {
Context context = null;
if (conCallbacks instanceof Activity)
context = conCallbacks;
else if (conListener instanceof Activity)
context = conListener;
else
throw new IllegalArgumentException();
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(conCallbacks)
.addOnConnectionFailedListener(conListener)
.addApi(LocationServices.API).build();
}
现在你可以通过
简单地调用它MyGoogleClass.buildGoogleApiClient(getActivity(), getActivity());
或者例如如果OnConnectionFailedListener
由片段实现
MyGoogleClass.buildGoogleApiClient(getActivity(), this);
你得到: