如何在公共接口上获取EditText(Layout.xml)的值?

时间:2016-03-15 12:06:05

标签: java android api android-studio interface

我还在学习Android编程,我需要帮助...
我使用Retrofit和Yahoo Weather API创建(来自在线教程)Weather App 但是这个应用程序只针对一个特定的城市 现在我想添加两个EditText(City,Country)并将这些内容放入API链接。

我做了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("......")

我收到错误:

  

错误:(20,42)错误:找不到符号方法findViewById(int)   错误:(24,145)错误:属性值必须是常量

2 个答案:

答案 0 :(得分:1)

我的朋友在这里试图说的是,只要你在VIEW对象之外,你就可以轻松地调用findViewById(),但是一旦你进入那个元素并且你正在寻找findViewById()你需要在VIEW对象之前写一下这个:

Context.findViewById ()  

或在你的情况下

WeatherAPI.findViewById ()

答案 1 :(得分:0)

只有当当前的Activity布局由 setContentView 设置时,才能在Activity对象上调用findViewById()。如果您通过其他方式添加布局,则需要布局的View对象并在其上调用findViewById()

像这样......

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