我一整天都被困在这上面。我目前已经实现了整个体系结构(实体、dao、存储库、带有livedata的viewmodel),一切正常。
我已经做了一个决定 recyclerView
,只有当数据仅来自单个表时,我才能使其工作。问题是 onBindViewHolder()
重复浏览单个对象的livedata列表。我想做的是,什么时候 onBindViewHolder()
到达例如。 Customer(productID as foreignkey)
,我想从 product
table在哪里 productID
对应。
我知道你不应该使用主线程来做这件事,但怎么做呢?我在google开发者网站上找不到关于这个的答案,所以我在这里问。为您提供我的代码示例:
观察员:
mCustomerViewModel = new ViewModelProvider(this).get(CustomerViewModel.class);
mCustomerViewModel.getAllCustomers().observe(getViewLifecycleOwner(), new Observer<List<Customer>>() {
@Override
public void onChanged(List<Customer> customers) {
adapter.setCustomers(customers);
}
});
回收器适配器类:
public class CustomerAdapter extends RecyclerView.Adapter<CustomerAdapter.CustomerHolder> {
private List<Customer> customers = new ArrayList<>();
private OnItemClickListener listener;
@NonNull
@Override
public CustomerHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.customer_recycler_item, parent, false);
return new CustomerHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull CustomerHolder holder, int position) {
Customer currentCustomer = customers.get(position);
holder.textView1.setText(currentCustomer.getCompanyName());
holder.textView2.setText(currentCustomer.getCountry());
holder.textView3.setText(currentCustomer.getPlace());
}
@Override
public int getItemCount() {
return customers.size();
}
public void setCustomers(List<Customer> customers) {
this.customers = customers;
notifyDataSetChanged();
}
class CustomerHolder extends RecyclerView.ViewHolder {
private final TextView textView1, textView2, textView3;
public CustomerHolder(@NonNull View itemView) {
super(itemView);
textView1 = itemView.findViewById(R.id.company_name_recycler);
textView2 = itemView.findViewById(R.id.company_country);
textView3 = itemView.findViewById(R.id.place);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = getAdapterPosition();
if (listener != null && position != RecyclerView.NO_POSITION) {
listener.onItemClick(customers.get(position));
}
}
});
}
}
public interface OnItemClickListener {
void onItemClick(Customer customer);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
}
这是可行的,但我似乎找不到一种方法来处理同一观察者中的外键数据/多个数据对象。
暂无答案!
目前还没有任何答案,快来回答吧!