我可以在 fragment 管理器中使用LocationListener吗?实际上,当我使用它时,它在这一行中给了我错误:lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, (android.location.LocationListener) this);
当我不将第四个参数强制转换为android.location.LocationListener
时,会给我错误...
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Speedometer extends Fragment implements LocationListener {
TextView txt;
public Speedometer(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.speedometer, container, false);
txt=(TextView)rootView.findViewById(R.id.speedometer);
LocationManager lm= (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, (android.location.LocationListener) this);
return rootView;
}
@Override
public void onLocationChanged(Location location) {
if(location==null){
txt.setText("-.- m/s");
} else {
float nCurrentSpeed=location.getSpeed();
txt.setText(nCurrentSpeed+"m/s");
}
}
}
最佳答案
我认为您错误地实现了只有一个抽象方法 com.google.android.gms.location.LocationListener
的 onLocationChanged
接口(interface)
您应该实现具有 4 个抽象方法的 android.location.LocationListener
onLocationChanged(Location location)
,onProviderDisabled(String provider)
,onProviderEnabled(String provider)
,onStatusChanged(String provider, int status, Bundle extras)