我正在尝试构建产品列表并动态更改产品状态,但是当我单击一个开关而另一个并返回以单击第一个时,它会在firebase中同时更改这两个值应用程序。我该如何解决这个问题?
我的产品片段类:
public class ProductsFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
Bundle savedInstanceState) {
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_product);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//Setting adapter and Holder
mAdapter = new FirebaseRecyclerAdapter<Product, ProductHolder>(options) {
@Override
public ProductHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_product_list, parent, false);
return new ProductHolder(view);
}
@Override
protected void onBindViewHolder(@NonNull ProductHolder holder, final int position,
@NonNull final Product model) {
holder.mAvailableSwitch.setChecked(model.isAvailable());
holder.mAvailableSwitch.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
updateStatus(model, b);
}
});
}
//Update product status
public void updateStatus(Product product,
boolean available) {
String key = product.getUid();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put(FirebaseUtils.getProductsPath() + key + "/available",
available);
mBaseRef = FirebaseUtils.getBaseRef();
mBaseRef.updateChildren(childUpdates);
}
mRecyclerView.setAdapter(mAdapter);
return view;
}
public class ProductHolder extends RecyclerView.ViewHolder {
public Switch mAvailableSwitch;
public ProductHolder(View view) {
super(view);
mAvailableSwitch = (Switch) view.findViewById(R.id.product_available);
}
}
item_product_list.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Switch
android:id="@+id/product_available"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
</FrameLayout>
答案 0 :(得分:0)
解决了! 只需在updateChildren()调用时添加addOnSuccessListener或addOnCompletedListener,并调用方法notifyItemChaged();
firestore示例:
holder.mAvailableSwitch.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, final boolean b) {
DocumentReference productRef =
new FirebaseUtils().productRef().document(model.getUid());
Map<String, Object> map = new HashMap<>();
map.put("available", b);
Log.d(TAG, "onCheckedChanged: " + model.getUid());
productRef.update(map).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
model.setAvailable(b);
notifyItemChanged(position, model);
}
});
}
});