2012-06-26 17 views
0

我想將緯度和經度的值返回到我的EditText s,我已經能夠使用Toast來做到這一點,但沒有通過EditText實現。好心幫Android TextBox

 // EditText latEditText = (EditText)findViewById(R.id.lat); 
//EditText lngEditText = (EditText)findViewById(R.id.lng); 

protected void showCurrentLocation(){ 
    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() 
          ); 
          Toast.makeText(LayActivity.this, message, 
            Toast.LENGTH_LONG).show(); 
     //latEditText.setText(nf.format(location.getLatitude()).toString()); 
     //lngEditText.setText(nf.format(location.getLongitude()).toString()); 
    } 
} 

private class MyLocationListener implements LocationListener{ 

    @Override 
    public void onLocationChanged(Location location) { 
     // TODO Auto-generated method stub 
     String message = String.format(
        "New Location \n Longitude: %1$s \n Latitude: %2$s", 
        location.getLongitude(), location.getLatitude() 
       ); 
       Toast.makeText(LayActivity.this, message, Toast.LENGTH_LONG).show(); 


     //latEditText.setText((int) location.getLatitude()); 
     //lngEditText.setText((int) location.getLongitude()); 

    } 

回答

1

只要latEditTextlngEditText變量具有一類範圍很廣,你可以簡單地讓您的活動實施LocationListener的:

public class Example extends Activity implements LocationListener 

然後這個工程:

public void onCreate(Bundle savedInstanceState) { 
    ... 
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
    if(location != null) 
     displayLocation(location); 
} 

public void onLocationChanged(Location location) { 
    if(location != null) 
     displayLocation(location); 
} 

public void displayLocation(Location location) { 
     latEditText.setText(location.getLatitude() + ""); 
     lngEditText.setText(location.getLongitude() + ""); 
    } 
} 

按要求

Soxxeh指出你的註釋代碼是傳遞setText()一個整數,這樣做會引用一個資源(比如你的strings.xml中的一個字符串的唯一id)。您想要像上面的方法或setText(String.valueOf(location.getLatitude()))一樣傳遞setText()實際的字符串。

希望有所幫助。

+0

可能想解釋它的工作原理;也就是說,因爲向'setText'提供一個'int'就意味着它是一個資源ID。 – Eric