How to keep selecting rows of RecyclerView during onClicks after pressing longClick? - android

I have a RecyclerView where I am selecting my rows only when I do onLongPress but what I want is that the first onLongClick will initiate the highlighting and then onClick on the row will select and de-select the particular rows and NOT onLongClick. After de-selecting the last selected row then onLongClick should initiate the highlighting again. I tried doing it with boolean variables. But it does not work. I am so confused. Any ideas?
This is what I have been upto.
if(onLongPressReceived) {
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!onClickAnotherPressReceived) {
onClickPressReceived = true;
mItems.get(holder.getAdapterPosition()).setmIsChecked(true);
notifyDataSetChanged();
onClickAnotherPressReceived = true;
}
}
});
holder.checkboxHolder.setVisibility(View.VISIBLE);
holder.mCheckBox.setChecked(mItems.get(position).getmIsChecked());
holder.mDeleteRow.setVisibility(View.VISIBLE);
if(mItems.get(holder.getAdapterPosition()).getmIsChecked()){
holder.cardView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.list_selected));
}else {
//holder.cardView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.list_long_pressed));
holder.checkboxHolder.setVisibility(View.INVISIBLE);
holder.mDeleteRow.setVisibility(View.INVISIBLE);
}
if(onClickPressReceived && !onLongAnotherPressReceived)
{
holder.checkboxHolder.setVisibility(View.VISIBLE);
holder.mCheckBox.setChecked(mItems.get(position).getmIsChecked());
holder.mDeleteRow.setVisibility(View.VISIBLE);
if(mItems.get(holder.getAdapterPosition()).getmIsChecked()){
holder.cardView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.list_selected));
}else {
//holder.cardView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.list_long_pressed));
holder.checkboxHolder.setVisibility(View.INVISIBLE);
holder.mDeleteRow.setVisibility(View.INVISIBLE);
}
}
//Checking whether a particular view is clicked or not
if(onClickAnotherPressReceived && !onLongAnotherPressReceived)
{
holder.cardView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.list_long_pressed));
holder.cardView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.list_unselected));
holder.mDeleteRow.setVisibility(View.INVISIBLE);
if (mItems.get(position).getmIsChecked()) {
holder.checkboxHolder.setVisibility(View.VISIBLE);
holder.mCheckBox.setChecked(true);
} else {
holder.checkboxHolder.setVisibility(View.GONE);
holder.mCheckBox.setChecked(false);
}
}
}
//Checking whether a particular view is clicked or not
else{
holder.cardView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.list_long_pressed));
holder.cardView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.list_unselected));
holder.mDeleteRow.setVisibility(View.INVISIBLE);
if (mItems.get(position).getmIsChecked()) {
holder.checkboxHolder.setVisibility(View.VISIBLE);
holder.mCheckBox.setChecked(true);
} else {
holder.checkboxHolder.setVisibility(View.GONE);
holder.mCheckBox.setChecked(false);
}
}
//Calls the interface method in Activity to respond to CheckBox changes
holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
updateMainClass.updateListBackground(holder.getAdapterPosition(), b);
}
});
/**
* <p>Responds to long press made on any row</p>
* <p>Checks the item on which long press is made
* sets the onLongPressReceived status to true and notify the adapter to refresh the list.</p>
*/
holder.cardView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
if(onLongAnotherPressReceived) {
onLongPressReceived = true;
mItems.get(holder.getAdapterPosition()).setmIsChecked(true);
notifyDataSetChanged();
onLongAnotherPressReceived = false;
}
return true;
}
});
//Calls the interface in Activity to remove the item from the List.
holder.mDeleteRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateMainClass.updateItemList(holder.getAdapterPosition());
}
});
}

I usually do this:
In your onBindViewHolder call bindView method of ViewHolder class:
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int position) {
((ViewHolder) viewHolder).bindView(getItem(position));
}
Then in your viewHolder class do keep instance of your entity:
public class ViewHolder extends RecyclerView.ViewHolder {
YOUR_OBJECT entity;
public ViewHolder(View itemView) {
super(itemView);
//initialize view here
}
public void bindView(ChannelEntity entity) {
this.entity = entity; // use this entity for longClickListener
//setOnClickListener || OnLongClickListener Here
}
}

Related

Store state for each item separately in RecyclerView

RecyclerView OnClick doesn't work properly. It has to change state to true or false. When I click on the first item it stores true and changes the text. But when I click on other item it changes the state to false because the first item set true, so the text doesn't change. How to store the states for each item separately?
boolean isChange = false;
#Override
public void onBindViewHolder(#NonNull final WindowViewHolder holder, int position) {
Window window = windowList.get(position);
holder.textViewTitle.setText(window.getTitle());
holder.textViewChecked.setText(window.getCheck());
holder.imageView.setImageDrawable(mCtx.getResources().getDrawable(window.getImage()));
////////////////////////////////////////////////
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isChange){
holder.parentLayout.setBackgroundColor(Color.parseColor("#66BB6A"));
holder.textViewChecked.setText("True");
isChange = true;
}
else {
holder.parentLayout.setBackgroundColor(Color.parseColor("#EEEEEE"));
holder.textViewChecked.setText("False");
isChange = false;
}
//Toast.makeText(mCtx, "Clicked", Toast.LENGTH_SHORT).show();
}
});
//////////////////////////////////////
}
I hope you have a setCheck() method for your Window object where you store the checked state. The isChange variable you use is not item specific so it keeps the value of the previous checked item.
From what I understand by your code you should do this:
#Override
public void onBindViewHolder(#NonNull final WindowViewHolder holder, int position) {
Window window = windowList.get(position);
holder.textViewTitle.setText(window.getTitle());
holder.textViewChecked.setText(window.getCheck());
holder.imageView.setImageDrawable(mCtx.getResources().getDrawable(window.getImage()));
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (window.getCheck().toString.equals("False")) {
window.setCheck("True");
holder.parentLayout.setBackgroundColor(Color.parseColor("#66BB6A"));
holder.textViewChecked.setText("True");
} else {
window.setCheck("False");
holder.parentLayout.setBackgroundColor(Color.parseColor("#EEEEEE"));
holder.textViewChecked.setText("False");
}
}
});
}
Why not to use Map?
I see you have some Window model. So you can create a map in you adapter and store a boolean value for each Window key:
private Map<Window, Boolean> map = new HashMap<>();
And then get value for the current value:
#Override
public void onBindViewHolder(#NonNull final WindowViewHolder holder, int position) {
Window window = windowList.get(position);
holder.textViewTitle.setText(window.getTitle());
holder.textViewChecked.setText(window.getCheck());
holder.imageView.setImageDrawable(mCtx.getResources().getDrawable(window.getImage()));
////////////////////////////////////////////////
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isChange = map.get(window);
if (!isChange){
holder.parentLayout.setBackgroundColor(Color.parseColor("#66BB6A"));
holder.textViewChecked.setText("True");
map.put(window, true);
}
else {
holder.parentLayout.setBackgroundColor(Color.parseColor("#EEEEEE"));
holder.textViewChecked.setText("False");
map.put(window, false);
}
//Toast.makeText(mCtx, "Clicked", Toast.LENGTH_SHORT).show();
}
});
//////////////////////////////////////
}

How can I have scrolling to last page working properly in a paginated scroll in android ListView

Attention! This question is not about dynamic loading of items into a very long ListView.
This is about adding PageUP and PageDown buttons to a ListView so that user can touch the button and scroll ListView page by page. Page means all fully and partially visible items on the screen.
I have partially implemented this in the following code, but my problem is that when I have lets say 10 items of approximately same height in the listview and 7 of them fit into the first page, then when I press PgDown button, user expects that item 8 to be on top of the screen (next page), but because there are only 10 items, ListView scrolls to the bottom of the list and because there is no extra scroll space I have item number 4 on top.
What is the best solution in this situation?
Should I add one item to the end of the list which will make the last page the height of the screen or there are any better options?
Here is my code:
public class cPaginatedListViewHelper {
Activity m_parentActivity;
private ListView mList;
//controls
private LinearLayout m_PagingLL;
//buttons
private ImageButton m_btnPrevPage;
private ImageButton m_btnNextPage;
private ImageButton m_btnExitPaginatedMode;
public cPaginatedListViewHelper(ListActivity mParent) {
this.m_parentActivity = mParent;
m_btnPrevPage=(ImageButton) mParent.findViewById(R.id.btnPrevPage);
m_btnNextPage=(ImageButton) mParent.findViewById(R.id.btnNextPage);
m_btnExitPaginatedMode =(ImageButton) mParent.findViewById(R.id.btnClosePage);
if(m_btnPrevPage!=null) {
m_btnPrevPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showSiblingPage(-1);
}
});
m_btnPrevPage.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
mList.smoothScrollToPosition(0);
return true;
}
}
);
}
if(m_btnNextPage!=null) {
m_btnNextPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showSiblingPage(1);
}
});
m_btnNextPage.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
mList.smoothScrollToPosition(mList.getCount());
return true;
}
}
);
}
m_btnExitPaginatedMode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setEnabled(false);
m_PagingLL.setVisibility(View.GONE);
}
});
mList=mParent.getListView();
m_PagingLL = (LinearLayout) mParent.findViewById(R.id.pageControls);
}
public void updateControlsVisibility()
{
ViewTreeObserver observer = mList.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (willMyListScroll()) {
boolean psm = isEnabled();
//enable or disable
m_PagingLL.setVisibility( psm ? View.VISIBLE : View.GONE);
((View)mList).setVerticalScrollbarPosition(psm ? View.SCROLLBAR_POSITION_LEFT: View.SCROLLBAR_POSITION_RIGHT);
}
else
{
m_PagingLL.setVisibility(View.GONE);
((View)mList).setVerticalScrollbarPosition(View.SCROLLBAR_POSITION_RIGHT);
}
}
});
}
private boolean willMyListScroll() {
try {
int pos = mList.getLastVisiblePosition();
if (mList.getChildAt(pos).getBottom() > mList.getHeight()) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
private void showSiblingPage(int shift)
{
if(mList!=null) {
int iScrollPageHeight = mList.getHeight();
mList.scrollListBy(iScrollPageHeight * shift);
}
}
public void setEnabled(boolean psm) {
MyApp.Pref.edit().putBoolean("PSModeEnabled", psm).commit();
}
public boolean isEnabled(){
return MyApp.Pref.getBoolean("PSModeEnabled", false);
}
public void pagedScrollEnableDisable() {
boolean pagingEnabled = isEnabled();
pagingEnabled=!pagingEnabled;
setEnabled(pagingEnabled);
m_PagingLL.setVisibility( pagingEnabled ? View.VISIBLE : View.GONE);
updateControlsVisibility();
}
}
I finished up with using ListView's footer with variable height as shown in the following code:
LayoutInflater inflater = m_parentActivity.getLayoutInflater();
m_footerView = inflater.inflate(R.layout.listview_paged_overscroll, mList, false );
ViewGroup.LayoutParams lp =m_footerView.getLayoutParams();
if(m_tvPageNum!=null) recalcPagination();
if(lp!=null) lp.height = m_extraScrollFooterHeight;
int iFooters = mList.getFooterViewsCount();
if(iFooters==0) mList.addFooterView(m_footerView);

android custom list view is refreshing after deleting first item from list

I am developing an android application, in that i using displaying pull notifications. I am getting the list of notification from backend and displaying in the form of custom list view.The problem is i am providing a button to delete particular notification from list view when ever i tried to delete the notification at any index it is deleting but after scrolling the entire list view is getting refreshed. How can i handle this?
one more thing is i am not using notifysetdatachange() anywhere.
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();
}
when you delete item form list that time remove that item form list and notify adapter.
like below code ... when i am delete any item form recycler view ..
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();
As per documentation you should not use this method with viewholder. you should use getAdapterposition() to get position of row.
getLayoutPosition added in version 22.1.0
int getLayoutPosition ()
Returns the position of the ViewHolder in terms of the latest layout
pass.
This position is mostly used by RecyclerView components to be
consistent while RecyclerView lazily processes adapter updates.
For performance and animation reasons, RecyclerView batches all
adapter updates until the next layout pass. This may cause mismatches
between the Adapter position of the item and the position it had in
the latest layout calculations.
LayoutManagers should always call this method while doing calculations
based on item positions. All methods in RecyclerView.LayoutManager,
RecyclerView.State, RecyclerView.Recycler that receive a position
expect it to be the layout position of the item.
If LayoutManager needs to call an external method that requires the
adapter position of the item, it can use getAdapterPosition() or
convertPreLayoutPositionToPostLayout(int).
In your use case, since your data is related to your adapter contents (and I assume that data is changed at the same time with adapter changes), you should be using adapterPosition.
Replace this lines
listAdapter.getEntries().remove(listAdapter.getEntries().get(viewHolder.getLayoutPosition()));
listAdapter.notifyItemRemoved(viewHolder.getLayoutPosition());
with
listAdapter.getEntries().remove(listAdapter.getEntries().get(viewHolder.getAdapterPosition()));
listAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());

After clicking a button view is updating on both items of recyclerview

I have a RecyclerView with post cards. So there is a like button in every post card. When I tap on a like button. Sometimes it works fine and updates on current item. But after some scroll when I tap on like button it updates on another item simultaneously.
It doesn't send that data to server. But, only the view is updated. Then when I scroll up and down again. The data goes back to normal.
Problem is in the following onClick method:-
FirebaseDatabase.getInstance().getReference().child("topics").child("likes").child(data.getId()).child(username).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child("like").exists()){
holder.like.setImageResource(R.drawable.ic_favorite_red_500_36dp);
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseDatabase.getInstance().getReference().child("topics").child("likes").child(data.getId()).child(username).child("like").removeValue();
}
});
}else if(dataSnapshot.child("dislike").exists()) {
holder.like.setImageResource(R.drawable.brokenheart);
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseDatabase.getInstance().getReference().child("topics").child("likes").child(data.getId()).child(username).child("dislike").removeValue();
}
});
}else{
holder.like.setImageResource(R.drawable.ic_favorite_border_red_500_36dp);
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseDatabase.getInstance().getReference().child("topics").child("likes").child(data.getId()).child(username).child("dislike").removeValue();
FirebaseDatabase.getInstance().getReference().child("topics").child("likes").child(data.getId()).child(username).child("like").setValue(true);
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
holder.like.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
FirebaseDatabase.getInstance().getReference().child("topics").child("likes").child(data.getId()).child(username).child("like").removeValue();
FirebaseDatabase.getInstance().getReference().child("topics").child("likes").child(data.getId()).child(username).child("dislike").setValue(true);
return true;
}
});
Full Adapter class https://pastebin.com/UnFGahWT
Try the following:-
Set Your on click listeners in the public ViewHolder(View itemView) method and make Your ViewHolder class implement the View.OnClickListener.
In Adapter add:
public Topic getItem(int position) {
return topics.get(position);
}
In ViewHolder's onClick method add:
int position = getAdapterPosition();
if (position == RecyclerView.NO_POSITION) return;
item = getItem(position);
Thus You will get the exact object You need to change or do something with it.

stoping the SwipeMenuLIstView to Swipe

i am using Swipe menu list View from the Githu
https://github.com/baoyongzhang/SwipeMenuListView
According to my project requirement i need to stop some list View to Swipe
for example i want to stop the list item on the postion 5
how i would do that
mListView.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {
#Override
public void onSwipeStart(int position) {
if (positon == 5) {
Toast.makeText(getApplicationContext(), "you are not Allow to Swipe", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onSwipeEnd(int position) {
}
});
You can create a private instance of the listener and than set it to the mListView if a condition is met and if you want to not allow the swiping to be active you can simply set the onSwipeListener to null like this:
private SwipeMenuListView.OnSwipeListener swipeListener = new SwipeMenuListView.OnSwipeListener() {
#Override
public void onSwipeStart(int i) {
}
#Override
public void onSwipeEnd(int i) {
}
});
if (condtion) {
Toast.makeText(getApplicationContext(), "you are not Allow to Swipe", Toast.LENGTH_SHORT).show();
//disable swiping
mListView.setOnSwipeListener(null);
}else{
//allow swiping
mListView.setOnSwipeListener(swipeListener);
}
you can use BaseSwipListAdapter and change condition according your requirments.
#Override
public boolean getSwipEnableByPosition(int position) {
if(position==5){
return false;
}
return true;
}

Categories

Resources