2016-03-15 35 views
1

我使用的是改造和雅虎天氣API仍然在學習Android的編程和我需要幫助...
創建(從網上的教程)的天氣應用。
但這個程序是隻爲一個特定的城市做。現在
我想添加兩個EditText上(城市,國家),並把這些內容納入API的鏈接。如何在公共界面上獲取EditText(Layout.xml)的值?

我activity_settings.xml

<EditText 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/etCity" 
    android:text="Zagreb" 
    android:layout_gravity="center_horizontal" /> 

和WeatherAPI.java

public interface WeatherAPI{ 

String BASE_URL = "https://query.yahooapis.com/v1/public/"; 
//String Zagreb = "Zagreb"; 
EditText cityText = (EditText) findViewById (R.id.etCity); 
String city = cityText.getText().toString(); 


@GET("yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22" + city + "%2C%20Hr%22)%20and%20u%3D'c'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys") 
Call<Weather> getWeather(); 

class Factory { 

    public static WeatherAPI service; 

    public static WeatherAPI getIstance() { 

     if (service == null) { 

      Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()) 
        .baseUrl(BASE_URL) 
        .build(); 


      service = retrofit.create(WeatherAPI.class); 
      return service; 
     } else { 
      return service; 
     } 
    } 
} 

做正如你可以看到我已經添加

EditText cityText = (EditText) findViewById (R.id.etCity); 
String city = cityText.getText().toString(); 

,並把城市變成@GET("......")

我得到的錯誤:

Error:(20, 42) error: cannot find symbol method findViewById(int) Error:(24, 145) error: attribute value must be constant

+0

創建Edittext對象後無法立即獲取文本。這將是永遠的空白 –

回答

0

調用活動對象上findViewById()如果當前活動佈局由的setContentView設置纔有效。如果通過一些其他手段增加一個佈局,那麼你需要的佈局視圖對象,並對其調用findViewById()

這樣的..

View v = inflater.inflate(id_layout); 
View innerView = v.findViewById(R.id.etCity); 
+0

謝謝你,只是我不明白的是:是否我需要添加視圖V = inflater.inflate(id_layout); ......在MainActivity.java或WeatherAPI.java? – croatan

+0

是的!你必須添加這個... – 2016-03-15 12:27:30

1

這裏什麼我的朋友想對我說,就是隻要你是視圖對象之外,你可以調用findViewById()容易,但是一旦你是元素裏,你是尋找findViewById()你需要前先查看對象之前,像這樣寫:

Context.findViewById() 

或在您的情況

WeatherAPI.findViewById()