眾所周知,java 是按值呼叫的,這里我們將 LinkedList 傳遞給 Adapter 類。像這樣
// this snippet is belongs to mainActivity
private final LinkedList<String> mWordList = new LinkedList<>();
createDataSet(); // Let's create a data set by calling this method
mRecyclerView = findViewById(R.id.recycler_view);
// lets create an adapter
mWordListAdapter = new WordListAdapter(this,mWordList);
mRecyclerView.setAdapter(mWordListAdapter); // connect the adapter to the view
mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); // pass a layout manager
并且配接器類有它自己的linkedList,它獲取我們從MainActivity傳遞的linkedList的資料。
// Adapter class
public class WordListAdapter extends RecyclerView.Adapter<WordListAdapter.WordViewHolder> {
private LinkedList<String> mwordList;
private LayoutInflater mInflater;
// get the data from mainActivity and the layout inflator
public WordListAdapter(Context context, LinkedList<String> wordList) {
mInflater = LayoutInflater.from(context);
mwordList = wordList;
}
// only showing up the needed snippets
}
并設定一個 onclicklistner 以在單擊這樣的專案時修改串列
@Override
public void onClick(View v) {
// get the position of the item that was clicked
int mPosition = getLayoutPosition();
// use this position to get the affected item in the wordlist
String element = mwordList.get(mPosition);
// change the data in the wordList
mwordList.set(mPosition,"cicked!" element);
// notify the adapter that the data has been chagned
// so recyclerVeiw can update it
mWordListAdapter.notifyDataSetChanged();
}
MainActivity 中還有一個 fab 按鈕來插入新資料
binding.fab.setOnClickListener(new View.OnClickListener() {
@Override // adding new word to the lsit
public void onClick(View view) {
int wordListSize = mWordList.size() 1;
mWordList.add(" " "word" wordListSize); // adding a new string element
mRecyclerView.getAdapter().notifyItemInserted(wordListSize); // notify dataset changed
mRecyclerView.smoothScrollToPosition(wordListSize); // scroll screen where we added new data
}
現在我的問題是,在沒有將更新的 LinkedList 傳遞給配接器類的情況下,這些資料是如何變化的,因為我們只在 notifyItemIntserted 中傳遞了更新串列的大小。我想知道后臺行程,因為它正在作業意味著有什么東西超出了我的想象。
uj5u.com熱心網友回復:
它關于參考。您的配接器和您的活動具有相同的參考,ArrayList因此如果您修改它,它將反映在兩者中。
public WordListAdapter(Context context, LinkedList<String> wordList) {
mInflater = LayoutInflater.from(context);
mwordList = wordList;
}
使用這段代碼mwordList = wordList;,您可以將相同的 Object 分配給一個新的參考變數,即mwordList. 參考變數不同,但它們指向的物件相同,即您在主 Activity 中創建的物件。
對于其他部分,如果您像下面那樣做,這只是為了解釋差異。
public WordListAdapter(Context context, LinkedList<String> wordList) {
mInflater = LayoutInflater.from(context);
mwordList = new LinkedList<>(wordList);
}
這不會反映您在 Activity 中的串列中所做的更改,因為現在兩者都指向不同的物件。mwordList我們為withnew關鍵字創建一個新物件。我希望這是有道理的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/430839.html
