一般來說,您應該嘗試將視圖和數據職責分開。所以,你需要的是從數據庫中獲取預先所有的對象,然後設置一個適配器,它看起來像以下:
final CustomAdapter adapter = new CustomAdapter();
adapter.setItems(mPersons);
mRecyclerView.setAdapter();
:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private final List<Person> objectList = new ArrayList<>();
@Override
public CustomAdapter.ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
final LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
return new ViewHolder(layoutInflater.inflate(R.layout.adapter_item, parent, false));
}
@Override
public void onBindViewHolder(final CustomAdapter.ViewHolder holder, final int position) {
holder.bindItem(objectList.get(position));
}
// Set the persons for your adapter
public void setItems(final List<Person> persons) {
objectList.addAll(persons);
notifyDataSetChanged();
}
@Override
public int getItemCount() {
return objectList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private final TextView mTextViewTitle;
private Object mObject;
public ViewHolder(final View itemView) {
super(itemView);
mTextViewTitle = (TextView) itemView.findViewById(R.id.view_item_textViewTitle);
mTextViewTitle.setText(mObject.getText());
}
private void bindItem(@NonNull final Person object) {
mObject = object;
}
}
}
然後你就可以將適配器通過綁定到RecyclerView
回答你的第二個問題(「過去,我們曾經有過listview和gridview,看起來它們現在合併成爲recyclerview。那麼,我該如何實現基於網格的recyclerview?」):
當綁定一個LayoutManager到RecyclerView你可以決定哪個一個你拿:
final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
或
final GridLayoutManager layoutManager = new GridLayoutManager(this, COLUMN_SPAN_COUNT);
mRecyclerView.setLayoutManager(layoutManager);
有幾個佈局管理。瞭解更多here。
UPDATE: 您不必裝載提前的所有項目,只需重命名setItems來爲addItems,你是好去
你不必使用任何列表:使用ItemBridgeAdapter + CursorObjectAdapter或直接綁定光標在你的自定義RecyclerView.Adapter – pskink
老實說,我不知道爲什麼CursorObjectAdapter是在「leanback」支持庫,它是專爲電視設備,imho它應該是任何「通用」支持庫的一部分 – pskink
@pskink我現在不得不解決這個問題。請您提供一個簡單的例子,說明如何在[我的]自定義RecyclerView.Adapter中直接綁定遊標?這將非常有幫助。謝謝。當你這樣做時,請在回覆的評論中加上標籤。感謝您的任何幫助,您可以提供。 –