簡體   English   中英

如何在 Adapter 類之外更新 RecyclerView Adapter

[英]How to update the RecyclerView Adapter outside the Adapter Class

我正在制作一個 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 請求和我的單例類都在工作,問題只是 RecyclerView。

非常感謝!

當你做

list = savedInfo.getResult();
notifyDataSetChanged();

每次創建新的列表實例時都不會在任何地方引用舊的。 所以,而不是分配到列表你應該做

list.clear()
list.addAll(savedInfo.getResult());
notifyDataSetChanged();

如果之前沒有完成,不要忘記初始化list

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM