最近我在 android 中使用 Volley 库。它工作正常,但我想知道更新 UI 的最有效方法。我有一个具有所有 Volley 方法的 Utils 类。现在我通过了所有将作为参数更新的 View ,但我读到我可以在我的 Activity 中实现监听器,然后将它们作为 Utils 类中的参数传递。
所以我的问题是:
哪个更有效以及为什么要像这样更新 UI:
public void getSettings(final TextView exampleView) {
JsonObjectRequest jsonRequest = new JsonObjectRequest(Method.GET,
url, (String) null, new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
final String setting = getSettingFromJSON(response);
exampleView.setText(setting);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError arg0) {
}
});
app.add(jsonRequest);
}
或者我在 Activity 中这样声明监听器:
Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
String setting = Utils.getSettingFromJSON(response);
exampleView.setText(setting);
}
};
然后我将它们作为参数传递到我的 utils 函数中,因此调用将是这样的:
utils.getSettings(listener);
代替:
utils.getSettings(exampleView);
提前致谢:)
最佳答案
为什么不使用像 EventBus 这样的东西呢?管理从请求到您的 Activity 的回传信息?这样您就可以将您的网络代码与您的 Activity/ View 分开。使用 EventBus 和 Volley 的基本思想如下:
- 注册一个类来接收某种类型的事件,在这种情况下可能是 Activity
- 在这个类中创建一个方法来处理这个事件,
exampleView.setText(设置)
。 - 将事件发布到总线,将 String 或 volley 错误发布到 截击听众。
有关更详细的示例,请查看此 blogpost或 Eventbus 的 github 页面。
关于java - 在 Volley 中更新 UI 的最有效方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31606450/