从列表中删除第一项后,android自定义列表视图刷新

时间:2018-03-14 07:16:24

标签: android android-recyclerview liferay liferay-6

My output is coming like this

我正在开发一个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();
}

2 个答案:

答案 0 :(得分:0)

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

     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();

答案 1 :(得分:0)

根据文档,您不应将此方法与viewholder一起使用。你应该使用getAdapterposition()来获取行的位置。

  在版本22.1.0中添加了

getLayoutPosition

     

int getLayoutPosition()

     

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

     

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

     

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

     

LayoutManagers应该在进行计算时始终调用此方法   根据项目位置。 RecyclerView.LayoutManager中的所有方法,   RecyclerView.State,RecyclerView.Recycler接收位置   期望它是项目的布局位置。

     

如果LayoutManager需要调用需要的外部方法   项的适配器位置,它可以使用getAdapterPosition()或   convertPreLayoutPositionToPostLayout(INT)。

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

替换此行

CREATE INDEX ON :Pin(id);
CREATE INDEX ON :Instance(id);

//CREATE CONSTRAINT ON (inst:Instance) ASSERT inst.Id IS UNIQUE;

USING PERIODIC COMMIT 10000
LOAD CSV WITH HEADERS FROM 'file:///home/sranga/work/Neo4j/work/signals.csv' AS line
MATCH (inst1:Pin { id: toInteger(line.Start_port)})
MATCH (inst2:Pin { id: toInteger(line.End_port)})
CREATE (inst1)-[:NET { id: toInteger(line.Signal_id),  Name: line.Name, Signed: toInteger(line.Signed), lbit: toInteger(line.Lbit), rbit: toInteger(line.Rbit)}]->(inst2);

<强>与

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