【问题标题】:How to get the Value of an EditText (Layout.xml) on public interface?如何在公共界面上获取 EditText (Layout.xml) 的值?
【发布时间】:2016-06-30 20:50:50
【问题描述】:

我仍在学习 Android 编程,我需要帮助...
我使用 Retrofit 和 Yahoo Weather API 创建(来自在线教程)天气应用程序。
但是这个应用程序只针对一个特定的城市。
现在我想添加两个 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) 错误:属性值必须是常量

【问题讨论】:

  • 创建 Edittext 对象后无法立即获取文本。它总是空白的

标签: java android api android-studio interface


【解决方案1】:

我的朋友在这里想说的是,只要您在 VIEW 对象之外,您就可以轻松调用findViewById(),但是一旦您在该元素内并且您正在寻找findViewById(),您需要编写在 VIEW 对象之前是这样的:

Context.findViewById ()  

或者在你的情况下

WeatherAPI.findViewById ()

【讨论】:

    【解决方案2】:

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

    像这样..

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

    【讨论】:

    • 谢谢,我唯一不明白的是:我是否需要在 MainActivity.java 或 WeatherAPI.java 上添加 View v = inflater.inflate(id_layout);.....
    猜你喜欢
    • 2016-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    • 2020-07-04
    • 2015-09-09
    相关资源
    最近更新 更多