我的目标是创建一个切换按钮来请求和删除android位置更新。如何修改此代码以通过单击相同的ImageButton删除位置更新?
ImageButton park_search = (ImageButton)findViewById(R.id.Park);
park_search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LocationServices.FusedLocationApi.requestLocationUpdates( MainActivity.mGoogleApiClient,
currentLocationRequest, new CurrentLocationListener(blocks) );
}
});
private class CurrentLocationListener implements LocationListener {
List<LatLng> pBlocks = new ArrayList<LatLng>();
CurrentLocationListener(List<LatLng> blocks){
this.pBlocks = blocks;
}
@Override
public void onLocationChanged(Location location) {
if(!MainActivity.isActive) {
Location endLoc = new Location("");
endLoc.setLongitude(pBlocks.get(0).longitude);
endLoc.setLatitude(pBlocks.get(0).latitude);
float distance = endLoc.distanceTo(location);
MainActivity.text_parking_info.setText("Dist = "+(int)distance);
if (distance < 50) {
//Do something
}
}else{
LocationServices.FusedLocationApi.removeLocationUpdates(MainActivity.mGoogleApiClient, this);
}
}
}
答案 0 :(得分:0)
将View.setTag设置为该按钮(ImageButton)即可实现此目的。
park_search.setTag(false);//setting default as false
park_search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
boolean status= !((boolean) view.getTag());// reverse the current status
if(status){
//start location updates.
LocationServices.FusedLocationApi.requestLocationUpdates( MainActivity.mGoogleApiClient,currentLocationRequest, new CurrentLocationListener(blocks) )
}else{
//remove location updates.
LocationServices.FusedLocationApi.removeLocationUpdates(MainActivity.mGoogleApiClient, this);
}
view.setTag(status);//update status
}
});