android-location显示在toast中但不在textview中显示

时间:2017-05-05 04:51:49

标签: android location

我的Android应用程序显示android中TOAST的最后/新位置。我添加了TextView以显示TextView中的位置,但该应用未显示在TextView中。我还正确地初始化了findViewById中的Activity

代码在这里:

public class home extends AppCompatActivity {

public static TextView SMS_textview;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1;
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000;
protected LocationManager locationManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home);
    SMS_textview = (TextView) findViewById(R.id.sms_text);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());

    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (location != null) {
        String message = String.format( "Current Location \n Longitude: %1$s \n Latitude: %2$s",location.getLongitude(), location.getLatitude());
        SMS_textview.setText(message);
        Toast.makeText(home.this, message,Toast.LENGTH_LONG).show();
        Log.i("Location Details",message);
    }
}
private class MyLocationListener implements LocationListener {
    public void onLocationChanged(Location location) {
        String message = String.format(
                "New Location \n Longitude: %1$s \n Latitude: %2$s",location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(home.this, message, Toast.LENGTH_LONG).show();
    }
    public void onStatusChanged(String s, int i, Bundle b) {
        Toast.makeText(home.this, "Provider status changed",Toast.LENGTH_LONG).show();
    }
    public void onProviderDisabled(String s) {
        Toast.makeText(home.this,"Provider disabled by the user. GPS turned off",Toast.LENGTH_LONG).show();
    }
    public void onProviderEnabled(String s) {
        Toast.makeText(home.this,"Provider enabled by the user. GPS turned on",Toast.LENGTH_LONG).show();
    }
} 
}

2 个答案:

答案 0 :(得分:0)

你没有在onLocationChanged方法中的textview中设置文本:

public void onLocationChanged(Location location) {
    String message = String.format(
            "New Location \n Longitude: %1$s \n Latitude: %2$s",location.getLongitude(), location.getLatitude()
    );
      // set location in textview
     SMS_textview.setText(message);
    Toast.makeText(home.this, message, Toast.LENGTH_LONG).show();
}

答案 1 :(得分:0)

将消息文本设置为TextView内的onLocationChanged,如下所示:

如果LocationManager不知道您的上一个位置,那么您的TextView无法显示位置,因此您必须在onLocationChanged内设置位置消息文字,以便将更新位置显示为{{1} }}

TextView