我正在使用Android Data Binding
實施Recycler View
及其各自的adapter
。問題是,在我見過的所有教程,它們初始化適配的數據與Collection
View model
的一類,像這樣:Android recyclerView數據綁定適配器數據
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements View.OnClickListener {
private ArrayList<ViewModel> items;
public RecyclerViewAdapter(ArrayList<ViewModel> items) {
this.items = items;
}
.....
}
但我想傳遞給Recycler View
數據是一個Collection
records
從我database
:
private ArrayList<Record> items;
我怎樣才能做到這一點?
在此先感謝!
編輯
li_item.xml
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="report"
type="viewmodel.ReportVM"/>
</data>
....
<TextView
android:id="@+id/tv_report_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:textSize="18sp"
android:paddingBottom="6dp"
android:text="@{report.name}"
tools:text="Report 1"
/>
....
ADAPTER
public class ReportRVAdapter extends RecyclerView.Adapter<ReportRVAdapter.ReportViewHolder> {
private List<ReportDb> data;
public ReportRVAdapter(final List<ReportDb> reportData) {
this.data = reportData;
}
@Override
public ReportRVAdapter.ReportViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.li_item, parent, false);
return new ReportViewHolder(v);
}
@Override
public void onBindViewHolder(final ReportViewHolder holder, final int position) {
ReportDb item = data.get(position);
holder.getBinding().setVariable(BR.name, item.getName());
holder.getBinding().setVariable(BR.contractor, item.getContractor());
//make binding happen immediately
holder.getBinding().executePendingBindings();
}
@Override
public int getItemCount() {
return data == null ? 0 : data.size();
}
public class ReportViewHolder extends RecyclerView.ViewHolder {
private ViewDataBinding binding;
public ReportViewHolder(final View rowView) {
super(rowView);
binding = DataBindingUtil.bind(rowView);
}
public ViewDataBinding getBinding() {
return binding;
}
}
}
模型視圖
public class ReportVM extends BaseObservable {
public String name;
public String contractor;
public ReportVM() {
}
@Bindable
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
@Bindable
public String getContractor() {
return contractor;
}
public void setContractor(final String contractor) {
this.contractor = contractor;
}
}
你怎麼從你的'記錄縮回數據'? –
我對數據庫做了一個查詢 – IrApp
在'onBindViewHolder'內執行它並不高效,所以你應該預先從數據庫讀取數據到mdoel我認爲 –