![](/img/trans.png)
[英]How can I refresh my recycler adapter after deleting it's item from an activity
[英]How can I reload/refresh the RecyclerView after deleting a item
我已经尝试了该站点的许多解决方案。 但仍然没有得到有效的解决方案。
这是我的片段 class。 我已经在这个 class 中设置了 Adpater。
public class FeedFragment extends Fragment {
RecyclerView recyclerView;
Context context;
FloatingActionButton addFeedButton;
private ArrayList<Feed> feeds;
FeedService feedService;
FeedRecyclerViewAdapter feedRecyclerViewAdapter;
TextView noDataTextView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_feed, container, false);
noDataTextView = view.findViewById(R.id.no_data_textView);
addFeedButton = view.findViewById(R.id.feed_floating_button);
System.out.println(getRole());
if (getRole().equals("ROLE_ADMIN")) {
addFeedButton.setVisibility(View.VISIBLE);
} else {
addFeedButton.setVisibility(View.GONE);
}
addFeedButton.setOnClickListener(v -> {
AddFeedFragment addFeedFragment = new AddFeedFragment();
FragmentManager fragmentManager = Objects.requireNonNull(getActivity()).getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_for_fragments, addFeedFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
});
recyclerView = view.findViewById(R.id.feedRecyclerView);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
initializeData();
return view;
}
public void initializeData() {
feedService = APIUtils.getFeedService();
feedService.getFeeds(AuthenticationToken()).enqueue(new Callback<List<Feed>>() {
@Override
public void onResponse(Call<List<Feed>> call, Response<List<Feed>> response) {
if (response.isSuccessful()) {
if (response != null) {
feeds = new ArrayList<>(response.body());
if(feeds.isEmpty()){
noDataTextView.setVisibility(View.VISIBLE);
}
else {
feedRecyclerViewAdapter = new FeedRecyclerViewAdapter(getActivity(), feeds);
recyclerView.setAdapter(feedRecyclerViewAdapter);
}
}
} else {
Toast.makeText(getContext(), "Unauthorized", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<List<Feed>> call, Throwable t) {
Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
private String AuthenticationToken() {
PrefManager prefManager = new PrefManager(getContext());
return prefManager.Authorization();
}
private String getRole() {
PrefManager prefManager = new PrefManager(getContext());
return prefManager.getRole();
}
}
这是我的适配器 class。
public class FeedRecyclerViewAdapter extends RecyclerView.Adapter<FeedRecyclerViewAdapter.FeedViewHolder> {
private ArrayList<Feed> feeds;
private Context context;
FeedService feedService;
ProfileService profileService;
public FeedRecyclerViewAdapter(Context context, ArrayList<Feed> feeds) {
this.feeds = feeds;
this.context = context;
}
public static class FeedViewHolder extends RecyclerView.ViewHolder {
CardView feedCardView;
TextView textViewTitle, textViewDescription, textViewPostBy, textViewPostDate, textViewMobile;
TextView textViewOption;
ImageView imageView,callButtonView;
public FeedViewHolder(@NonNull @NotNull View itemView) {
super(itemView);
feedCardView = itemView.findViewById(R.id.feedCardView);
imageView=itemView.findViewById(R.id.user_photo);
callButtonView=itemView.findViewById(R.id.callButton);
textViewTitle = itemView.findViewById(R.id.feedTitle);
textViewDescription = itemView.findViewById(R.id.feedDescription);
textViewPostBy = itemView.findViewById(R.id.postBy);
textViewPostDate = itemView.findViewById(R.id.posDate);
textViewMobile = itemView.findViewById(R.id.mobile);
textViewOption = itemView.findViewById(R.id.three_dot);
}
}
@NonNull
@NotNull
@Override
public FeedRecyclerViewAdapter.FeedViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.feed_custom_layout, parent, false);
FeedViewHolder fvh = new FeedViewHolder(view);
return fvh;
}
@Override
public void onBindViewHolder(@NonNull @NotNull FeedViewHolder holder, int position) {
final long itemId = feeds.get(position).getId();
final String profilePicName=feeds.get(position).getUser().getProfile().getProfilePic();
profileService= APIUtils.getProfileService();
profileService.loadProfile(AuthenticationToken(),profilePicName).enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
System.out.println(response.code());
if(response.isSuccessful()){
try {
byte[] bytes=response.body().bytes();
Bitmap bitmap= BitmapFactory.decodeByteArray(bytes,0,bytes.length);
Glide.with(context).asBitmap()
.load(bitmap)
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.ALL))
.placeholder(R.drawable.account_circle).into(holder.imageView);
} catch (IOException e) {
e.printStackTrace();
}
}
else{
Toast.makeText(context,"Load failed",Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(context,t.getMessage(),Toast.LENGTH_LONG).show();
}
});
holder.textViewTitle.setText(feeds.get(position).getFeedTitle());
holder.textViewDescription.setText(feeds.get(position).getFeedDescription());
holder.textViewPostBy.setText(feeds.get(position).getUser().getFullName());
holder.textViewPostDate.setText(feeds.get(position).getPostDate());
holder.textViewMobile.setText(feeds.get(position).getUser().getMobile());
holder.callButtonView.setOnClickListener(v -> {
String phone=feeds.get(position).getUser().getMobile();
String dialCall="tel:"+phone;
Intent intent=new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(dialCall));
context.startActivity(intent);
});
ItemAnimation.animateFadeIn(holder.itemView, position);
if(getRole().equals("ROLE_ADMIN")){
holder.textViewOption.setOnClickListener(v -> {
PopupMenu popupMenu = new PopupMenu(context, holder.textViewOption);
popupMenu.inflate(R.menu.update_delete_menu);
popupMenu.setOnMenuItemClickListener(item -> {
switch (item.getItemId()) {
case R.id.popup_update:
AlertDialog.Builder builder= new AlertDialog.Builder(v.getContext());
builder.setTitle(R.string.dialog_feed_update_title);
builder.setPositiveButton(R.string.dialog_yes, (dialog, which) -> {
Intent intent = new Intent(context, FeedUpdateActivity.class);
intent.putExtra("feedId", itemId);
context.startActivity(intent);
});
builder.setNegativeButton(R.string.dialog_no, (dialog, which) -> {
Toast.makeText(context.getApplicationContext(),"Canceled",Toast.LENGTH_LONG).show();
});
builder.create().show();
break;
case R.id.popup_delete:
AlertDialog.Builder builder1 = new AlertDialog.Builder(v.getContext());
builder1.setTitle(R.string.dialog_delete_title);
builder1.setPositiveButton(R.string.dialog_yes, (dialog, which) -> {
feedService = APIUtils.getFeedService();
feedService.deleteFeed(itemId, AuthenticationToken()).enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
Toast.makeText(context.getApplicationContext(), "Deleted", Toast.LENGTH_LONG).show();
notifyDataSetChanged();
} else {
Toast.makeText(context.getApplicationContext(), "Delete Failed", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(context.getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
});
builder1.setNegativeButton(R.string.dialog_no, (dialog, which) -> {
Toast.makeText(context.getApplicationContext(), "Canceled", Toast.LENGTH_LONG).show();
});
builder1.create().show();
break;
}
return false;
});
popupMenu.show();
});
}
else{
holder.textViewOption.setVisibility(View.GONE);
}
}
@Override
public void onAttachedToRecyclerView(@NotNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
@Override
public int getItemCount() {
return feeds.size();
}
private String AuthenticationToken() {
PrefManager prefManager = new PrefManager(context.getApplicationContext());
return prefManager.Authorization();
}
private String getRole() {
PrefManager prefManager = new PrefManager(context.getApplicationContext());
return prefManager.getRole();
}
}
在这里,我调用了notifyDataSetChange
。 但无法刷新Fragment arraylist
中设置的arraylist。 在适配器 class 中完成删除后,如何刷新片段中的arraylist
。
您可以使用 DiffUtil 将数据加载到 recyclerview 适配器中。 对于点击监听器,您可以在片段本身中实现该方法(在适配器 class 中创建接口,在片段中实现方法,并将接口的实例传递给适配器的构造函数)。 现在,您可以通过更改原始列表来尽可能多地操作数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.