LocationListener in fragment

ぐ巨炮叔叔 提交于 2019-12-10 04:27:24

问题


Can I use LocationListener with LocationManager in fragment? Actually when I use it, it gives me error in this line:

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, (android.location.LocationListener) this);

and when I do not casts the 4th parameter to android.location.LocationListener it gives me error...

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");
        }   
    }
}

回答1:


I think you have mistakenly implemented com.google.android.gms.location.LocationListener interface that has just one 1 abstract method onLocationChanged

You should rather implement android.location.LocationListener that has 4 abstract methods

onLocationChanged(Location location),

onProviderDisabled(String provider),

onProviderEnabled(String provider),

onStatusChanged(String provider, int status, Bundle extras)



来源:https://stackoverflow.com/questions/30233219/locationlistener-in-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!