【问题标题】:android custom list view is refreshing after deleting first item from list从列表中删除第一项后,android自定义列表视图正在刷新
【发布时间】:2018-08-22 15:02:19
【问题描述】:

我正在开发一个 android 应用程序,因为我使用显示拉取通知。我从后端获取通知列表并以自定义列表视图的形式显示。问题是我提供了一个按钮来从列表视图中删除特定通知,当我尝试删除它正在删除的任何索引处的通知但之后滚动整个列表视图正在刷新。我该如何处理?

还有一件事是我没有在任何地方使用 notifysetdatachange()

public class NotificationListViewHolder extends BaseListAdapter.ViewHolder {
    //timeStamp, userName;
    public final CircleImageView profilePicture;
    public final TextView timeStamp;
    public final ImageView deleteNotification;
    public final ProgressBar progressBar;
    public final RelativeLayout notificationListItem;
    public TextView requirement;
    public LinearLayout clickableArea;
    NotificationListViewHolder viewHolder;
    NotificationListAdapter listAdapter;


    public NotificationListViewHolder(View view, BaseListAdapterListener listener, NotificationListAdapter listAdapter) {
        super(view, listener);
        requirement = view.findViewById(R.id.requirement);
        profilePicture = view.findViewById(R.id.profile_picture);
        notificationListItem = view.findViewById(R.id.notification_list_item);
        deleteNotification = view.findViewById(R.id.delete_notification);
        progressBar = view.findViewById(R.id.progressBar);
        clickableArea = view.findViewById(R.id.clickable_area);
        timeStamp = view.findViewById(R.id.time_stamp);
        this.listAdapter = listAdapter;

    }

    public void bind(final Notification entry, NotificationListViewHolder holder) {
        try {
            if (holder.notificationListItem.getTag() == null) {
                holder.notificationListItem.setTag(holder);
            } else {
                viewHolder = (NotificationListViewHolder) holder.notificationListItem.getTag();
            }

            viewHolder.progressBar.setVisibility(entry.isSelected()
                    ? View.VISIBLE : View.GONE);
            viewHolder.deleteNotification.setVisibility(entry.isSelected()
                    ? View.GONE : View.VISIBLE);


            viewHolder.requirement.setText(entry.getRequirement());
            if (entry.getRoleName().equals("")) {
                viewHolder.timeStamp.setText(TimeFormat.getTimeStamp(entry.getTimestamp(), TimeFormatTypes.FORMAT_DESCRIPTION) + "");
            } else {
                viewHolder.timeStamp.setText(entry.getRoleName() + " - " + TimeFormat.getTimeStamp(entry.getTimestamp(), TimeFormatTypes.FORMAT_DESCRIPTION) + "");
            }
            if (viewHolder.profilePicture != null && !entry.getProfileUrl().equalsIgnoreCase("")) {
                Picasso.with(D4E.getContext()).load(D4E.getContext().getResources().getString(R.string.liferay_server) + entry.getProfileUrl()).placeholder(R.drawable.default_profile_pic)
                        .error(R.drawable.default_profile_pic).into(viewHolder.profilePicture);
            }

            if (entry.getType() == 1) { // light grey , my post notifications || other post notification
                viewHolder.notificationListItem.setBackgroundColor(Color.parseColor("#C8FAD2"));
                viewHolder.requirement.setTextColor(Color.parseColor("#030303"));
            } else if (entry.getType() == 2) {
                // the posts by others
            /*    viewHolder.notificationListItem.setBackgroundColor(Color.parseColor("#DCDCDC"));
                viewHolder.requirement.setTextColor(Color.parseColor("#030303"));*/
            } else if (entry.getType() == 0) { // dark grey , admin
                viewHolder.notificationListItem.setBackgroundColor(Color.parseColor("#FAFAC8"));
                viewHolder.requirement.setTextColor(Color.parseColor("#030303"));
            }


            viewHolder.clickableArea.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    entry.setSelected(true);
                    deleteNotification();
                    viewHolder.progressBar.setVisibility(View.VISIBLE);
                    viewHolder.deleteNotification.setVisibility(View.GONE);
                }

                private void deleteNotification() {
                    Session session = SessionContext.createSessionFromCurrentSession();
                    session.setCallback(new Callback() {
                        @Override
                        public void inBackground(Response response) {
                            ((Activity) D4E.getContext()).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        viewHolder.progressBar.setVisibility(View.GONE);
                                        AnimatorUtil.animate(viewHolder/*, true*/);
                                        listAdapter.getEntries().remove(listAdapter.getEntries().get(viewHolder.getLayoutPosition()));
                                        listAdapter.notifyItemRemoved(viewHolder.getLayoutPosition());
                                        UserInfoController.initializeUserInfoController().getUserInfo().setNotificationCount(listAdapter.getEntries().size());

                                       /* listAdapter.notifyDataSetChanged();
                                        listAdapter.getEntries().remove(listAdapter.getEntries().get(viewHolder.getLayoutPosition()));
                                        listAdapter.notifyItemRemoved(viewHolder.getLayoutPosition());
                                        listAdapter.notifyItemRangeChanged(viewHolder.getLayoutPosition(), listAdapter.getEntries().size());
                                        listAdapter.notifyDataSetChanged();
                                        UserInfoController.initializeUserInfoController().getUserInfo().setNotificationCount(listAdapter.getEntries().size());*/
                                        /*if (listAdapter.getEntries().size() == 0)
                                            (() D4E.getContext()).onNoListItem();*/

                                    } catch (Exception e) {
                                        Log.e("Ex:Noti_List_Adp", "" + e.toString());
                                    }
                                }
                            });
                        }

                        @Override
                        public void doFailure(Exception exception) {
                            viewHolder.progressBar.setVisibility(View.GONE);
                            viewHolder.deleteNotification.setVisibility(View.VISIBLE);
                            entry.setSelected(false);
                        }
                    });
                    try {
                        new DeccategoryService(session).DeleteNotification(Long.parseLong(entry.getNotificationId()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

          /*  if (holder.notificationListItem.getTag() == null) {
                holder.notificationListItem.setTag(holder);
            } else {
                viewHolder = (NotificationListViewHolder) holder.notificationListItem.getTag();
            }*/

           /* viewHolder.clickableArea.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    entry.setSelected(true);
                    // adapter.removeItem(entry,getAdapterPosition());
                    openDeleteNotification();
                    viewHolder.progressBar.setVisibility(View.VISIBLE);
                    viewHolder.deleteNotification.setVisibility(View.GONE);
                }


                private void openDeleteNotification() {
                    Session session = SessionContext.createSessionFromCurrentSession();
                    session.setCallback(new Callback() {
                        @Override
                        public void inBackground(Response response) {
                            ((Activity) D4E.getContext()).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    viewHolder.progressBar.setVisibility(View.GONE);
                                    adapter.removeItem(entry, getAdapterPosition());

                                }
                            });
                        }

                        @Override
                        public void doFailure(Exception exception) {
                            viewHolder.progressBar.setVisibility(View.GONE);
                            viewHolder.deleteNotification.setVisibility(View.VISIBLE);
                            entry.setSelected(false);
                        }
                    });
                    try {
                        new DeccategoryService(session).DeleteNotification(Long.parseLong(entry.getNotificationId()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });*/

            viewHolder.progressBar.setVisibility(entry.isSelected()
                    ? View.VISIBLE : View.GONE);
            viewHolder.deleteNotification.setVisibility(entry.isSelected()
                    ? View.GONE : View.VISIBLE);


            viewHolder.requirement.setText(entry.getRequirement());
            if (entry.getRoleName().equals("")) {
                viewHolder.timeStamp.setText(TimeFormat.getTimeStamp(entry.getTimestamp(), TimeFormatTypes.FORMAT_DESCRIPTION) + "");
            } else {
                viewHolder.timeStamp.setText(entry.getRoleName() + " - " + TimeFormat.getTimeStamp(entry.getTimestamp(), TimeFormatTypes.FORMAT_DESCRIPTION) + "");
            }
            if (viewHolder.profilePicture != null && !entry.getProfileUrl().equalsIgnoreCase("")) {
                Picasso.with(D4E.getContext()).load(D4E.getContext().getResources().getString(R.string.liferay_server) + entry.getProfileUrl()).placeholder(R.drawable.default_profile_pic)
                        .error(R.drawable.default_profile_pic).into(viewHolder.profilePicture);
            }

            if (entry.getType() == 1) {
                viewHolder.notificationListItem.setBackgroundColor(Color.parseColor("#F2F2F2"));
                viewHolder.requirement.setTextColor(Color.parseColor("#030303"));
            } else if (entry.getType() == 2) {
/*                viewHolder.notificationListItem.setBackgroundColor(Color.parseColor("#DCDCDC"));
                viewHolder.requirement.setTextColor(Color.parseColor("#030303"));*/
            } else {
                viewHolder.notificationListItem.setBackgroundColor(Color.parseColor("#FFFFFF"));//admin post color
            }


            //    FontStyle.getInstance().FontStyleByGroupOfIds(view.getContext(), new int[]{R.id.notification_list_item}, view);


        } catch (Exception e) {
            Log.e("Exception", e.toString());
        }

    }


    public void createDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(D4E.getContext());
        builder.setTitle("Alert!");
        builder.setMessage("Message from Admin");
        builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.cancel();
            }
        });
        builder.show();
    }

}
public class Notifications extends Scheduler implements ScreenletListListener, SearchView.OnQueryTextListener, NoListListener, UpdateLogout {
public static boolean isInSettingsPage;
public static long notificationId;
public static String notificationSearchKeyword = "";
public static boolean notificationSearchActivated = false;
public static boolean navigatedFromPush = false;
ArrayList<digital.engineers.club.models.Notifications> notificationsModel;
BottomSheetDialog dialog;
View dialogView;
Menu menu;
GenericScreenlet screenlet;
SearchView searchView;
MenuItem searchMenuItem;
LinearLayout container;
View screenletView, noIntimationView;
private boolean shudRefreshOnResume = false;
//Push test

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_notifications);
    setContext(this);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    container = findViewById(R.id.ns);
    D4E.setContext(this);

    FontStyle.getInstance().setContext(this);
    getSupportActionBar().setTitle(FontStyle.getInstance()
            .getSpannableString(getSupportActionBar().getTitle().toString()));

    container = findViewById(R.id.container);
    noIntimationView = View.inflate(this, R.layout.no_list_intimation, null);
    refreshNotifications();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.notification_menu, menu);
    this.menu = menu;

    final MenuItem menuItem = menu.findItem(R.id.nsettings);
    BitmapDrawable icon = (BitmapDrawable) menuItem.getIcon();
    Drawable drawable = DrawableCompat.wrap(icon);
    DrawableCompat.setTint(drawable, getResources().getColor(R.color.white));

    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    searchMenuItem = menu.findItem(R.id.search);
    searchView = (SearchView) searchMenuItem.getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setOnQueryTextListener(this);
    searchView.setSubmitButtonEnabled(false);
    searchView.setIconifiedByDefault(true);
    return super.onCreateOptionsMenu(menu);

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        if (isInSettingsPage) {
            resetNotificationPage();
            isInSettingsPage = false;
        } else {
            if (navigatedFromPush) {
                startActivity(new Intent(this, HomeScreen.class));
                navigatedFromPush = false;
            } else
                finish();
        }
    } else if (item.getItemId() == R.id.search) {
    } else if (item.getItemId() == R.id.nsettings) {
        isInSettingsPage = true;
        loadSettings();
    }
    return super.onOptionsItemSelected(item);
}

public void loadSettings() {
    FontStyle.getInstance().setContext(this);
    getSupportActionBar().setTitle(FontStyle.getInstance().getSpannableString("Notification Settings"));
    container.removeAllViews();
    if (searchMenuItem.isActionViewExpanded())
        searchMenuItem.collapseActionView();
    menu.getItem(0).setVisible(false);
    menu.getItem(1).setVisible(false);
    getFragmentManager().beginTransaction().replace(R.id.container, new NotificationSettingsFragment()).commit();
}

private void openbootomsheet() {
    dialog = new BottomSheetDialog(Notifications.this);
    dialogView = View.inflate(Notifications.this, R.layout.search_posts, null);
    dialogView.findViewById(R.id.search_by_time_layout);
    dialog.setContentView(dialogView);
    ((Spinner) dialogView.findViewById(R.id.posted_time)).setAdapter(new ArrayAdapter<String>(Notifications.this, android.R.layout.simple_list_item_1,
            android.R.id.text1,
            getResources().getStringArray(R.array.day_search)));
    ((Spinner) dialogView.findViewById(R.id.role)).setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
            android.R.id.text1,
            getResources().getStringArray(R.array.roles)));
    dialog.show();
    dialogView.findViewById(R.id.close_button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    dialogView.findViewById(R.id.search_button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
}

@Override
public void onListPageReceived(int startRow, int endRow, List<Object> entries, int rowCount) {
    //  Toast.makeText(this,"Success",Toast.LENGTH_LONG).show();
    //UserInfoController.initializeUserInfoController().getUserInfo().setNotificationCount(0);
    UserInfoController.initializeUserInfoController().getUserInfo().setNotificationCount(entries.size());
    if (entries.size() == 0) {
        showNoNotificationIntimation();
    }

    /*screenlet.setVisibility(entries.size() > 0 ? View.VISIBLE : View.GONE);
    ((LinearLayout) findViewById(R.id.no_list_layout)).setVisibility(entries.size() > 0 ? View.GONE : View.VISIBLE);*/

}

@Override
public void onListItemSelected(Object element, View view) {
    Notification notification = (Notification) element;
    if (notification != null) {
        if (((Notification) element).getType() != 0) {
            notificationId = Long.parseLong(notification.getNotificationId());
            NewPost.postType = (SessionContext.getUserId() == Long.parseLong(notification.getPostedUserId())) ?
                    getResources().getString(R.string.post_type_my_post) :
                    getResources().getString(R.string.post_type_relevant_post);

            Map<String, Object> postMap = new HashMap<>();

            postMap.put("threadId", notification.getThreadId());
            postMap.put("profileUrl", SessionContext.getUserId() == Long.parseLong(notification.getPostedUserId()) ?
                    UserInfoController.initializeUserInfoController().getUserInfo().getProfileUrl() :
                    notification.getProfileUrl());
            postMap.put("firstName", notification.getFirstName());
            postMap.put("lastName", notification.getLastName());
            postMap.put("categoryId", notification.getCategoryId());
            postMap.put("timestamp", notification.getTimestamp());
            postMap.put("subject", notification.getSubject());
            postMap.put("threadStatus", notification.getThreadStatus());
            postMap.put("userId", String.valueOf(SessionContext.getUserId()));
            postMap.put("postedUserId", notification.getPostedUserId());
            postMap.put("userName", notification.getUserName());
            postMap.put("roleName", notification.getRoleName());


            // postMap.put("attachment",notification.getAttachment());

            ViewThread.post = new Post(postMap);
            ViewThread.post.setAttachment(notification.getAttachment());
            NewPost.currentPostId = ViewThread.post.getThreadId();
            NewPost.currentPosition = (SessionContext.getUserId() == Long.parseLong(notification.getPostedUserId())) ?
                    0 : 1; // View Pager position
            NewPost.postedUserId = Long.parseLong(ViewThread.post.getPostedUserId());
            HomeScreen.categoryId = Long.parseLong(ViewThread.post.getCategoryId());

            Intent intent = new Intent(Notifications.this, ViewThread.class);
            intent.putExtra("THREAD", ViewThread.post);
            startActivity(intent);
        } else {
            createDialog(notification.getRequirement());
        }
    }
}

@Override
public void error(Exception e, String userAction) {
    //  Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show();
}

@Override
public void onListPageFailed(int startRow, Exception e) {
    //   Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show();
}

@Override
public void interactorCalled() {

}

@Override
protected void onResume() {
    super.onResume();

    if (isScreenOn(this) && hasTimedOut) {
        initializeTimer();
        resetTimeOut();
        startSessionTimeCountDown();
    }


    if (shudRefreshOnResume) {
        if (!isInSettingsPage) {
            refreshNotifications();
            shudRefreshOnResume = false;
        } else {
            loadSettings();
        }
    }


}

@Override
protected void onPause() {
    super.onPause();
    shudRefreshOnResume = true;
}

@Override
public boolean onQueryTextSubmit(String query) {
    return true;
}

@Override
public boolean onQueryTextChange(String newText) {
    if (newText.length() > 3) {
        notificationSearchKeyword = newText;
        notificationSearchActivated = true;
        refreshNotifications();
    } else if (newText.length() == 0) {
        notificationSearchKeyword = "";
        notificationSearchActivated = false;
        refreshNotifications();
    }
    return true;
}

public void refreshNotifications() {
    container.removeAllViews();
    View notificationScreenlet = View.inflate(this, R.layout.notification_list_screenlet, null);
    screenlet = notificationScreenlet.findViewById(R.id.notification_list_screenlet);
    screenlet.setPagination();
    screenlet.setListener(this);
    container.addView(notificationScreenlet);
}

public void resetNotificationPage() {
    FontStyle.getInstance().setContext(this);
    getSupportActionBar().setTitle(FontStyle.getInstance().getSpannableString("Notifications"));
    menu.getItem(0).setVisible(true);
    menu.getItem(1).setVisible(true);
    refreshNotifications();
    notificationSearchActivated = false;
}


private void setItemsVisibility(Menu menu, MenuItem exception, boolean visible) {
    for (int i = 0; i < menu.size(); ++i) {
        MenuItem item = menu.getItem(i);
        if (item != exception) item.setVisible(visible);
    }
}

@Override
public void onBackPressed() {
    notificationSearchActivated = false;
    if (isInSettingsPage) {
        resetNotificationPage();
        isInSettingsPage = false;
    } else {
        if (navigatedFromPush) {
            startActivity(new Intent(this, HomeScreen.class));
            navigatedFromPush = false;
        } else
            finish();
    }

}

public void createDialog(String message) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(D4E.getContext());
    builder.setTitle("Message from Admin");
    builder.setMessage(message);
    builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.cancel();
        }
    });
    builder.show();
}

public void showNoNotificationIntimation() {
    container.removeAllViews();
    noIntimationView.findViewById(R.id.no_list_layout).setLayoutParams(new LinearLayout.LayoutParams
            (LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
    container.addView(noIntimationView);
}

@Override
public void onNoListItem() {
    showNoNotificationIntimation();
}

@Override
public void onUpdatedLogoutToServer() {
    //if (SessionHelper.initializeSessionHelper().logout()) {
    DisplayDialog.display(this);
    /*} else {
        Log.e("LogoutErr", "Homescreen: Unable to Logout");
    }*/
}

@Override
public void onError(Exception e) {
    Toast.makeText(getApplicationContext(), "Unable to logout from scheduler", Toast.LENGTH_SHORT).show();
}

【问题讨论】:

  • 有什么理由标记这个 liferay-6 liferay-7?
  • 我正在使用 list screentlet 来显示通知列表
  • 在两个版本中?
  • 我使用的不仅仅是liferay 6

标签: android android-recyclerview liferay liferay-6


【解决方案1】:

当您删除项目表单列表时,删除该项目表单列表并通知适配器。 就像下面的代码......当我删除任何项目表单回收站视图..

     yourlist.remove(yourlist.get(yourlist.indexOf(data))); // common data that pass in list.if List<String> that pass string data if object them pass that object data.
                            youradapter.notifyDataSetChanged();

【讨论】:

  • 这个东西我已经在我的代码中使用 listAdapter.getEntries().remove(listAdapter.getEntries().get(viewHolder.getLayoutPosition()));
【解决方案2】:

根据文档,您不应将此方法用于查看器。您应该使用 getAdapterposition() 来获取行的位置。

getLayoutPosition 在 22.1.0 版本中添加

int getLayoutPosition()

根据最新布局返回 ViewHolder 的位置 通过。

这个位置主要是 RecyclerView 组件用来 一致,而 RecyclerView 懒惰地处理适配器更新。

出于性能和动画原因,RecyclerView 批量处理所有 适配器更新直到下一个布局通过。这可能会导致不匹配 在项目的适配器位置和它所在的位置之间 最新的布局计算。

LayoutManagers 在计算时应该总是调用这个方法 根据物品位置。 RecyclerView.LayoutManager 中的所有方法, RecyclerView.State, RecyclerView.Recycler 接收一个位置 期望它是项目的布局位置。

如果 LayoutManager 需要调用需要 项目的适配器位置,它可以使用 getAdapterPosition() 或 convertPreLayoutPositionToPostLayout(int).

在您的用例中,由于您的数据与您的适配器内容相关(我假设数据与适配器更改同时更改),您应该使用adapterPosition

替换这行

listAdapter.getEntries().remove(listAdapter.getEntries().get(viewHolder.getLayoutPosition()));
listAdapter.notifyItemRemoved(viewHolder.getLayoutPosition());

listAdapter.getEntries().remove(listAdapter.getEntries().get(viewHolder.getAdapterPosition()));
listAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());

【讨论】:

  • 你能分享输出屏幕截图或 gif 吗?
猜你喜欢
  • 1970-01-01
  • 2013-10-03
  • 1970-01-01
  • 2021-01-06
  • 1970-01-01
  • 2012-05-05
  • 1970-01-01
  • 2015-05-16
  • 2021-03-05
相关资源
最近更新 更多