我正在制作一个 Android 应用程序,它允许用户在 editText 中输入关键字,当他们点击提交时,下面的 recyclerview 将显示 API 请求的结果。
我的 recyclerView 适配器类中有一个 updateList() 方法
list = savedInfo.getResult(); // get updated list from a singleton class
notifyDataSetChanged(); // update the recyclerView
我在成功发出API请求后调用此方法。但是,它现在可以工作,recyclerView 没有更新。
mSearchBox是editText,允许用户输入关键字,这里是onEditorAction,它会调用API,如果调用成功,它会调用UpdateList(),然后适配器会获取更新的列表并执行notifyDataSetChanged()
mSearchBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_DONE) {
HttpRequest httpRequest = new HttpRequest();
mHomeText.setText(textView.getText());
try {
if (httpRequest.makeCall(textView.getText().toString())){
adapter.updateList();
}
else {
// showing error message
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
return false;
}
});
此外,这是设置适配器的步骤
final ResultListAdapteradapter = new ResultListAdapter();
mResult.setAdapter(adapter);
mResult.setLayoutManager(new LinearLayoutManager(getContext()));
调试步骤:我尝试设置断点,发现 API 请求和我的 Singleton 类都正常工作,问题只是 RecyclerView。
非常感谢!
最佳答案
当你这样做时
list = savedInfo.getResult();
notifyDataSetChanged();
每次创建新的列表实例时,旧的列表实例都不会在任何地方被引用。因此,您应该这样做,而不是分配给列表
list.clear()
list.addAll(savedInfo.getResult());
notifyDataSetChanged();
如果之前没有初始化过,请不要忘记初始化list
。
关于java - 如何在Adapter类之外更新RecyclerViewAdapter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63627231/