【发布时间】:2020-09-12 15:32:31
【问题描述】:
我正在尝试将与 recyclerview 位于同一片段中的视图的可见性动态设置为当 recyclerview 变空时不可见。问题是我正在从 recyclerview 中删除一个项目适配器,而可见性必须在片段内设置。我还实现了“滑动删除”recyclerview 项目,但那是在带有 rv 的片段内,并且视图需要变得不可见并且它工作正常。
从适配器中删除:
holder.shoppingCartDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int holderPosition = holder.getAdapterPosition();
removeItem(holderPosition, v.getContext());
MainActivity.shoppingCartDatabase.shoppingCartDao().delete(currentItem);
}
});
private void removeItem(int position, Context context) {
shoppingCartList.remove(position);
if (shoppingCartList.isEmpty()) {
Toast.makeText(context, "Nu mai exista niciun produs in cos", Toast.LENGTH_LONG).show();
// SET VISIBILITY
}
notifyItemRemoved(position);
}
从片段中删除-删除最后一项后可见性发生了变化:
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
MainActivity.shoppingCartDatabase.shoppingCartDao().delete(shoppingCartList.get(position));
shoppingCartList.remove(position);
shopAdapter.notifyDataSetChanged();
verifyIfRecyclerViewIsEmpty(shopAdapter, recyclerView);
}
}).attachToRecyclerView(recyclerView);
verifyIftheRecyclerViewIsEmpty(shopAdapter, recyclerView) 是可见性的方法:
private void verifyIfRecyclerViewIsEmpty(RecyclerView.Adapter adapter, RecyclerView recyclerView) {
if (adapter.getItemCount() == 0) {
constraintLayout.setVisibility(View.GONE);
recyclerView.setVisibility(View.GONE);
textView.setVisibility(View.VISIBLE);
btnAdd.setVisibility(View.VISIBLE);
} else {
constraintLayout.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.VISIBLE);
textView.setVisibility(View.GONE);
btnAdd.setVisibility(View.GONE);
}
}
【问题讨论】:
-
你的代码到底有什么问题?
-
@Zain 我正在尝试设置适配器内部视图的可见性,因为我在其中进行删除,但问题是视图位于片段中而不是适配器中.
标签: android android-studio android-recyclerview visibility