Notifydatasetchanged() is causing blinking within child recyclerview - android

I am having an extremely hard time trying to disable animations for a nested recyclerview whenever the parent recyclerview calls ondatasetchanged(). So some context a recyclerview that holds tinder-like swap cards and a nested recyclerview within each card to scroll through user images. After every swipe ondatasetchanged is called and causing a bad flickering within the nested recyclerview. I have tried to disabled the animations from both parent and child recyclerviews and pretty much anything I can think of at this point. The code below is my view holder for each card.
public class CardStackHolder extends RecyclerView.ViewHolder implements OnItemSwipePercentageListener {
ImageButton profileInfoBtn;
RecyclerView images_recyclerView;
PagerSnapHelper snapHelper;
ProfileImagesAdapter imagesAdapter;
String profileName;
TextView nameBox;
TextView ageBox;
TextView workBox;
List<String> list;
public CardStackHolder(final View itemView) {
super(itemView);
profileInfoBtn = (ImageButton) itemView.findViewById(R.id.ID_datingRecyclerView_profileInfoBtn);
profileInfoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//show profile info dialog
User_Info_Dialog dialog = User_Info_Dialog.getDialog(mHostId, mCurrentProfile.getGender(), mCurrentProfile.getOrientation(), mCurrentProfile.getInterestedIn(), mCurrentProfile.getIntro(), mCurrentProfile.getStatus());
dialog.show(getChildFragmentManager(), "");
}
});
nameBox = (TextView) itemView.findViewById(R.id.ID_datingRecyclerView_profile_name);
ageBox = (TextView) itemView.findViewById(R.id.ID_datingRecyclerView_profile_age);
images_recyclerView = (RecyclerView) itemView.findViewById(R.id.ID_datingRecyclerView_profileImagesRecyclerView);
RecyclerView.ItemAnimator animator = images_recyclerView.getItemAnimator();
((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
animator.setChangeDuration(0);
animator.setRemoveDuration(0);
images_recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(images_recyclerView);
workBox = (TextView) itemView.findViewById(R.id.ID_datingRecyclerView_profile_work);
}
public void onBind(Context context, User_Profile profile) {
getImages(profile.getProfileId());
profileName = profile.getFirst_name();
profileName = profileName.substring(0, 1).toUpperCase() + profileName.substring(1);
nameBox.setText(profileName);
ageBox.setText(profile.getAge());
String workStr = profile.getWork();
workStr = workStr.substring(0, 1).toUpperCase() + workStr.substring(1);
workBox.setText(workStr);
mCurrentProfile = profile;
}
public void getImages(String id) {
mFirebaseDatabase.getReference().child("profile_pictures").child(id).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
list = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (snapshot.hasChild("dating_card_imagePath")) {
list.add(snapshot.child("dating_card_imagePath").getValue().toString());
}
}
imagesAdapter = new ProfileImagesAdapter(list);
imagesAdapter.setHasStableIds(true);
images_recyclerView.setAdapter(imagesAdapter);
} else {
// no images found for profile
imagesAdapter = new ProfileImagesAdapter();
imagesAdapter.setHasStableIds(true);
images_recyclerView.setAdapter(imagesAdapter);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onItemSwipePercentage(double percentage) {
//log percentage moved
//Log.d("Enchanted", Double.toString(percentage));
if (percentage > -0.20 && percentage < 0.20) {
swipeResultImageView.setVisibility(View.GONE);
} else if (percentage < 0.20) {
swipeResultImageView.setImageResource(R.drawable.ic_swipe_no_like);
swipeResultImageView.setVisibility(View.VISIBLE);
} else if (percentage > -0.20) {
swipeResultImageView.setImageResource(R.drawable.ic_swipe_like);
swipeResultImageView.setVisibility(View.VISIBLE);
}
}
}
code below is my adapter
//CardStack Adapter
class CardStackAdapter extends RecyclerView.Adapter<CardStackHolder> {
LayoutInflater mInflater;
List<User_Profile> profileList;
RecyclerView.RecycledViewPool ImagePool;
public CardStackAdapter(Context context, List<User_Profile> list) {
mInflater = LayoutInflater.from(context);
profileList = new ArrayList<>(list);
ImagePool = new RecyclerView.RecycledViewPool();
}
#Override
public CardStackHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_item_dating_profile_card, parent, false);
return new CardStackHolder(view);
}
#Override
public void onBindViewHolder(final CardStackHolder holder, int position) {
holder.images_recyclerView.setRecycledViewPool(ImagePool);
profileList.get(position).setItemId(holder.getItemId());
holder.onBind(mContext, profileList.get(position));
}
public void removeTopItem() {
profileList.remove(0);
notifyDataSetChanged();
}
public void addItemToTop() {
profileList.add(0, mPreviousProfile);
notifyItemInserted(0);
}
public void updateProfileList(List<User_Profile> p) {
ImagePool.clear();
profileList.clear();
profileList.addAll(p);
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public int getItemCount() {
return profileList.size();
}
#Override
public long getItemId(int position) {
return profileList.get(position).getItemId();
}
}

Why are you calling notifyDataSetChanged() inside removeTopItem()?
Using notifyDataSetChanged() recreate all views again. You can notify recyclerview in which position item removed.
public void removeTopItem() {
profileList.remove(0);
notifyItemRemoved(0);
}

Related

DiffUtil with Async callback only displays list once and doesn't update

I am using DiffUtil async callback to update my list.
The problem is that it only displays the dataset once, at the first call. Later, when the dataset updates, the list only displays the items that were initially displayed. So the problem is that the dataset updates, but the list is stuck on its first state.(With the items that were initially created)
The dataset is being updated via a button click initiated by the user, this is how it looks:
private void updateUsersList() {
#Override
public void onResponse(JSONArray response) { // the JSON ARRAY response of user ids ["uid1", "uid334", "uid1123"]
for (int i = 0; i < response.length(); i++) {
try {
String userKey = response.get(i).toString(); // the currently iterated user id
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userKeyRef = rootRef.child("users").child(userKey); // reference to currently iterated user
ValueEventListener listener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
myDataset.add(new User(dataSnapshot.getKey(), dataSnapshot.child("imageUrl").getValue().toString())); //add new user: id and image url
mAdapter.updateList(myDataset);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
userKeyRef.addListenerForSingleValueEvent(listener);
}
catch (JSONException e) { Log.d(TAG, "message " + e); }
}
}
And this is my adapter using async DiffUtil:
public class MyAdapter extends RecyclerView.Adapter {
private AsyncListDiffer<User> mAsyncListDiffer;
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView singleItemTextView;
public ImageView singleItemImage;
public View layout;
public ConstraintLayout constraintLayout;
public MyViewHolder(View v) {
super(v);
layout = v;
singleItemImage = (ImageView) v.findViewById(R.id.icon);
singleItemTextView = (TextView) v.findViewById(R.id.singleitemtv);
constraintLayout = (ConstraintLayout) v.findViewById(R.id.nbConstraintLayout);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter() {
DiffUtil.ItemCallback<User> diffUtilCallback = new DiffUtil.ItemCallback<User>() {
#Override
public boolean areItemsTheSame(#NonNull User newUser, #NonNull User oldUser) {
return newUser.getUserId().equals(oldUser.getUserId());
}
#Override
public boolean areContentsTheSame(#NonNull User newUser, #NonNull User oldUser) {
return newUser.equals(oldUser);
}
};
mAsyncListDiffer = new AsyncListDiffer<>(this, diffUtilCallback);
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.nb_image_view, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
User user = mAsyncListDiffer.getCurrentList().get(position);
Uri userImage = user.getImageUrl();
Log.d("test123", "user uri: " + userImage.toString());
holder.singleItemTextView.setText(user.getUserId());
Glide.with(holder.itemView.getContext() /* context */)
.load(userImage)
.into(holder.singleItemImage);
holder.constraintLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(v.getContext(), DisplayUserActivity.class);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mAsyncListDiffer.getCurrentList().size();
}
public void updateList(ArrayList<User> newList) {
mAsyncListDiffer.submitList(newList);
}
}
So why does my dataset update, but the list is stuck on first update only?

Make onClickListener accessible in Activity from RecyclerViewAdapter

Actually in my RecyclerView i'm able to create Child items by programmatically adding view and TextView.
I even have a onClickListener for my parent item from the same RecyclerView and i've added a onClick method for my Child view's but now my main issue is how can i use the Child onClick in my Activity?
Here is my Adapter code
public class AdapterPTERM extends RecyclerView.Adapter<AdapterPTERM.ExampleViewHolder> {
private List<ItemPTERM> mExampleList;
private final LayoutInflater mInflater;
private OnItemClickListener mListener;
// ONCLICK FOR THE CHILD ITEMS
private View.OnClickListener varientClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.getTag()!= null){
int position = (int) v.getTag();
}
}
};
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_pterm,parent,false);
return new ExampleViewHolder(v,mListener);
}
AdapterPTERM(Context context, List<ItemPTERM> exampleList){
mExampleList = exampleList;
mInflater = LayoutInflater.from(context);
}
#Override
public void onBindViewHolder(#NonNull final ExampleViewHolder holder, final int position) {
final ItemPTERM item = mExampleList.get(position);
holder.desc.setText(item.getBtnName());
holder.qta.setText(String.valueOf(item.getQuant()));
holder.variantsContainer.removeAllViews();
// CREATING CHILD ITEM
List<Variant> variants = item.getVariants();
if (variants != null && variants.size() > 0){
for(Variant v : variants){
View vView = mInflater.inflate(R.layout.variant_layout,holder.variantsContainer,false);
TextView nameTV = vView.findViewById(R.id.variant_name);
nameTV.setText(v.getName());
vView.setTag(position);
vView.setOnClickListener(varientClickListener);
holder.variantsContainer.addView(vView);
}
}
// NOT IMPORTANT (CHANGING FIELDS COLOR)
if(position % 2 == 0 ){
holder.itemView.setBackgroundColor(Color.parseColor("#C0C0C0"));
}else if(position % 2 == 1){
holder.itemView.setBackgroundColor(Color.parseColor("#D3D3D3"));
}
}
#Override
public int getItemCount() {
return mExampleList.size();
}
public class ExampleViewHolder extends RecyclerView.ViewHolder {
public TextView desc;
public TextView qta;
private LinearLayout variantsContainer;
ExampleViewHolder(View itemView, final OnItemClickListener listener) {
super(itemView);
desc = itemView.findViewById(R.id.Desc);
qta = itemView.findViewById(R.id.Qta);
variantsContainer = itemView.findViewById(R.id.ll_child_items);
// onClick method for Parent Item
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
public void removeItem(int position) {
mExampleList.remove(position);
notifyItemRemoved(position);
}
public void removeVariant(int position,int positionbtn){
mExampleList.get(positionbtn).getVariants().remove(position);
notifyDataSetChanged();
}
}
While here is my code from the Activity where i build my RecyclerView and here i'm using the onClick for the parent for make appear an AlertDialog but i would be able to make appear that AlertDialog by clicking onChild instead of parent.
public void buildTopRecyclerView() {
mRecyclerViewTOP = findViewById(R.id.listView);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
exampleAdapter = new AdapterPTERM(this,dummyDataItems);
mRecyclerViewTOP.setLayoutManager(mLayoutManager);
mRecyclerViewTOP.setAdapter(exampleAdapter);
mRecyclerViewTOP.setHasFixedSize(true);
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
if (direction == ItemTouchHelper.RIGHT) {
customAllertDelete(position);
exampleAdapter.notifyItemChanged(position);
}
if (direction == ItemTouchHelper.LEFT) {
customAllertQuantity(position);
exampleAdapter.notifyItemChanged(position);
}
}
}).attachToRecyclerView(mRecyclerViewTOP);
exampleAdapter.setOnItemClickListener(new AdapterPTERM.OnItemClickListener() {
#Override
public void onItemClick(int position) {
if (dummyDataItems.get(position).getVariants() != null) {
customAlertVar(position);
}else {
//
}
}
});
}
SOLVED
I just had to remove
// ONCLICK FOR THE CHILD ITEMS
private View.OnClickListener varientClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.getTag()!= null){
int position = (int) v.getTag();
}
}
};
From my adapter as it was handling another click and was blocking the AlertDialog and even removed the
vView.setTag(position);
vView.setOnClickListener(varientClickListener);

how programmatically select item by position in adapter (android)

I want to select an item by position in adapter programmatically
in my project i have an activity that get categories , now i want to select an item form this adapter automatic.
final result is :
after Home activity have been lunched when user clicks on the button and lunch the second activity that getting my categories from web service in the adapter and then select an item by position at adapter and run third activity that shown the content of the item.
Here is my codes
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FragmentCategory extends Fragment {
private View root_view, parent_view;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipe_refresh;
private AdapterCategory mAdapter;
private Call<CallbackCategories> callbackCall = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_category, null);
parent_view = getActivity().findViewById(R.id.main_content);
swipe_refresh = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_category);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewCategory);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setHasFixedSize(true);
//set data and list adapter
mAdapter = new AdapterCategory(getActivity(), new ArrayList<Category>());
recyclerView.setAdapter(mAdapter);
// on item list clicked
mAdapter.setOnItemClickListener(new AdapterCategory.OnItemClickListener() {
#Override
public void onItemClick(View v, Category obj, int position) {
ActivityCategoryDetails.navigate((ActivityMain) getActivity(), v.findViewById(R.id.lyt_parent), obj);
}
});
// on swipe list
swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mAdapter.resetListData();
requestAction();
}
});
requestAction();
return root_view;
}
private void displayApiResult(final List<Category> categories) {
mAdapter.setListData(categories);
swipeProgress(false);
if (categories.size() == 0) {
showNoItemView(true);
}
}
private void requestCategoriesApi() {
API api = RestAdapter.createAPI();
callbackCall = api.getAllCategories();
callbackCall.enqueue(new Callback<CallbackCategories>() {
#Override
public void onResponse(Call<CallbackCategories> call, Response<CallbackCategories> response) {
CallbackCategories resp = response.body();
if (resp != null && resp.status.equals("ok")) {
displayApiResult(resp.categories);
} else {
onFailRequest();
}
}
#Override
public void onFailure(Call<CallbackCategories> call, Throwable t) {
if (!call.isCanceled()) onFailRequest();
}
});
}
private void onFailRequest() {
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
showFailedView(true, getString(R.string.failed_text));
} else {
showFailedView(true, getString(R.string.no_internet_text));
}
}
private void requestAction() {
showFailedView(false, "");
swipeProgress(true);
showNoItemView(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestCategoriesApi();
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if(callbackCall != null && callbackCall.isExecuted()){
callbackCall.cancel();
}
}
private void showFailedView(boolean flag, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_category);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (flag) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction();
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_category);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_category);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipe_refresh.setRefreshing(show);
return;
}
swipe_refresh.post(new Runnable() {
#Override
public void run() {
swipe_refresh.setRefreshing(show);
}
});
}
}
`
Update : AdapterCategory Codes
public class AdapterCategory extends RecyclerView.Adapter<AdapterCategory.ViewHolder> {
private List<Category> items = new ArrayList<>();
private Context ctx;
private OnItemClickListener mOnItemClickListener;
public interface OnItemClickListener {
void onItemClick(View view, Category obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
// Provide a suitable constructor (depends on the kind of dataset)
public AdapterCategory(Context context, List<Category> items) {
this.items = items;
ctx = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView name;
public TextView post_count;
public LinearLayout lyt_parent;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.name);
post_count = (TextView) v.findViewById(R.id.post_count);
lyt_parent = (LinearLayout) v.findViewById(R.id.lyt_parent);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final Category c = items.get(position);
holder.name.setText(Html.fromHtml(c.title));
holder.post_count.setText(c.post_count+"");
holder.lyt_parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, c, position);
}
}
});
}
public void setListData(List<Category> items){
this.items = items;
notifyDataSetChanged();
}
public void resetListData() {
this.items = new ArrayList<>();
notifyDataSetChanged();
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return items.size();
}
}

Removing recyclerview items from the Adapter

I have two tabs (fragments), NewOrders and FinishedOrders, I'm populating the orders via Volley requests, now each item inside the New Orders tab has a SwipeLayout which show a clickable textview that makes the order finished, and move it to the other tab (backend stuff..), and I got this working perfectly,
The problem is when I click to finish, the recyclerview isn't updated once the request sent successfully, I have to do pull-to-refresh so it would update..! it seems easy to solve, but the issue is handling the swipelayout listener done inside onBindView method inside the adapter..!! that's only place to access it according to the library I'm using (I guess)..! on the other hand refreshing and populating the list happens in the NewOrder tab fragment..!
So how can I make the item to be removed from the list after the click and becomes updated..?!
Any thoughts..!?
My Adapter Class + ViewHolder
Note: the implemented methods in the adapter are required because of the interface of SwipeLayout library
public class OrdersDataAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
implements SwipeAdapterInterface, SwipeItemMangerInterface {
protected SwipeItemRecyclerMangerImpl mItemManger = new SwipeItemRecyclerMangerImpl(this);
public Context context;
ArrayList<OrderPresenter> orders;
public OrdersDataAdapter(ArrayList<OrderPresenter> orders, Context context) {
this.orders = orders;
this.context = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_card, parent, false);
return new NewOrderVH(v);
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
final OrderPresenter order = this.orders.get(position);
final NewOrderVH vh1 = (NewOrderVH) holder;
vh1.setData(orders.get(position));
mItemManger.bindView(vh1.itemView, position);
vh1.swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
vh1.swipeLayout.addDrag(SwipeLayout.DragEdge.Left,
vh1.swipeLayout.findViewById(R.id.bottom_wrapper));
if (order.isFinished()) {
vh1.swipeLayout.setSwipeEnabled(false);
vh1.setBadge("DONE");
vh1.setBadgeColor(order.getBadgeColor());
} else {
vh1.finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// get the clicked item position?
final int position = vh1.getAdapterPosition();
// these responsible for the request which make the order finished
OrderPresenter order = orders.get(position);
OrderRepository.setOrderFinURL(order.getID());
OrderRepository.FinishOrder(order.getID(), context);
/*the commented three lines below didn't help with the problem*/
// notifyItemChanged(position);
// notifyItemRemoved(position);
// notifyDataSetChanged();*/
order.setStatus(order.getStatusText(Order.FINISHED));
}
});
}
}
#Override
public int getItemCount() {
return orders.size();
}
public class NewOrderVH extends RecyclerView.ViewHolder {
SwipeLayout swipeLayout;
private TextView finish;
private CardView orderCard;
TextView Badge;
private ImageView cusPic;
private TextView cusName;
private TextView CusAdress;
private TextView vendorsNum;
private TextView itemsNum;
private TextView time;
private TextView emptyView;
public NewOrderVH(View itemView) {
super(itemView);
Badge = (TextView) itemView.findViewById(R.id.badge);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
finish = (TextView) itemView.findViewById(R.id.finish);
orderCard = (CardView) itemView.findViewById(R.id.OrderCard);
cusPic = (ImageView) itemView.findViewById(R.id.cusPic);
cusName = (TextView) itemView.findViewById(R.id.cusName);
CusAdress = (TextView) itemView.findViewById(R.id.CusAdress);
vendorsNum = (TextView) itemView.findViewById(R.id.vendorsNum);
itemsNum = (TextView) itemView.findViewById(R.id.itemsNum);
time = (TextView) itemView.findViewById(R.id.time);
emptyView = (TextView) itemView.findViewById(R.id.empty_view);
orderCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), OrderDetails.class);
v.getContext().startActivity(intent);
}
});
}
public void setData(final OrderPresenter data) {
time.setText(data.getOrderTime());
cusName.setText(data.getFullName());
vendorsNum.setText(data.getVendorsCount());
itemsNum.setText(data.getItemsCount());
CusAdress.setText(data.getFullAddress());
Picasso.with(context).load(data.getCustomerPicture()).into(cusPic);
}
public void setBadgeColor(int drawable) {
this.Badge.setBackgroundResource(drawable);
}
public void setBadge(String badge) {
this.Badge.setText(badge);
}
}
#Override
public int getSwipeLayoutResourceId(int position) {
return R.id.swipe;
}
#Override
public void openItem(int position) {
}
#Override
public void closeItem(int position) {
}
#Override
public void closeAllExcept(SwipeLayout layout) {
}
#Override
public void closeAllItems() {
}
#Override
public List<Integer> getOpenItems() {
return null;
}
#Override
public List<SwipeLayout> getOpenLayouts() {
return null;
}
#Override
public void removeShownLayouts(SwipeLayout layout) {
}
#Override
public boolean isOpen(int position) {
return false;
}
#Override
public Attributes.Mode getMode() {
return null;
}
#Override
public void setMode(Attributes.Mode mode) {
}
}
My NewOrder Fragment
Note: the FinishedOrders tab (fragment) does the same thing as new order but filters the current the Finished status.
public class NewOrdersTab extends Fragment {
RecyclerView recyclerView;
OrdersDataAdapter adapter;
private SwipeRefreshLayout swiperefresh;
private TextView emptyView;
ArrayList<OrderPresenter> modelData;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.new_orders_tab_frag, container, false);
modelData = new ArrayList<>();
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
swiperefresh = (SwipeRefreshLayout) rootView.findViewById(R.id.swiperefresh);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
swiperefresh.setColorSchemeResources(R.color.colorPrimary, R.color.color_error, R.color.colorInfo);
adapter = new OrdersDataAdapter(modelData, getActivity());
emptyView = (TextView) rootView.findViewById(R.id.empty_view);
recyclerView.setAdapter(adapter);
adapter.setMode(Attributes.Mode.Single);
OrderRepository.fetchOrders("awaiting-shipment", getActivity(), new DataFetch() {
#Override
public void onResponse(ArrayList<OrderPresenter> data) {
swiperefresh.setRefreshing(true);
if (data.size() != 0) {
swiperefresh.setRefreshing(true);
emptyView.setVisibility(View.GONE);
modelData.clear();
modelData.addAll(data);
adapter.notifyDataSetChanged();
} else {
emptyView.setVisibility(View.VISIBLE);
emptyView.setText(getString(R.string.No_New_Orders));
}
swiperefresh.setRefreshing(false);
}
});
return rootView;
}
}
I figured it out, I just added these two lines after I make the request..!
orders.remove(position);
notifyItemRemoved(position);
//notifyDataSetChanged(position);

Control button behaviour according to change in checkbox of Recyclerview

I am having one recycler view with an adapter class. In the single item view there is a checkbox also. In my layout view it contains one button and recycler view mentioned above. When i checks on any check box in the view the button should get activated (Changing the color to active). When nothing is selected on the view button should become in the form of deactivated. How can i possible? Any example? Code is below
public class PlatformAdapter extends RecyclerView.Adapter<PlatformAdapter.ViewHolder> {
ArrayList<Batch> batches;
ArrayList<CourseSlug> courses;
boolean isInstituteStudent;
public void setBatches(ArrayList<Batch> batches) {
this.batches = batches;
notifyDataSetChanged();
}
public void setCourses(ArrayList<CourseSlug> courses) {
this.courses = courses;
notifyDataSetChanged();
}
public ArrayList<CourseSlug> getCourses() {
return courses;
}
public ArrayList<Batch> getBatches() {
return batches;
}
public void setInstituteStudent(boolean instituteStudent) {
isInstituteStudent = instituteStudent;
}
public boolean isInstituteStudent() {
return isInstituteStudent;
}
public PlatformAdapter() {
courses = new ArrayList<>();
batches = new ArrayList<>();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_cell_platform_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
if (isInstituteStudent) {
Batch batch = batches.get(position);
holder.enrolment.setText(batch.getName());
holder.selectEnrollment.setChecked(batch.isPreselect());
} else {
final CourseSlug course = courses.get(position);
holder.enrolment.setText(course.getName());
holder.selectEnrollment.setChecked(course.isPreselect());
}
}
#Override
public int getItemCount() {
return isInstituteStudent ? batches.size() : courses.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView enrolment;
CheckBox selectEnrollment;
public ViewHolder(final View itemView) {
super(itemView);
enrolment = (TextView) itemView.findViewById(R.id.tv_entrollment);
selectEnrollment = (CheckBox) itemView.findViewById(R.id.cb_select_entrollment);
selectEnrollment.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
int index = getLayoutPosition();
if(isInstituteStudent) {
Batch batch = batches.get(index);
batch.setPreselect(b);
} else {
CourseSlug course = courses.get(index);
course.setPreselect(b);
}
}
});
}
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
}
My Recyclerview and button implemented class is given below
public class SelectPlatform extends BaseActivity {
PlatformAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_platform);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
initializeViews(
findViewById(R.id.ll_content_area),
findViewById(R.id.tv_error),
findViewById(R.id.pb_loading)
);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv_platform);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new PlatformAdapter();
recyclerView.setAdapter(adapter);
private void renderCourses(ArrayList<CourseSlug> courses) {
getSupportActionBar().setTitle("Select Courses");
TextView title = (TextView) findViewById(R.id.tv_select_enrollment);
title.setText("Select your courses");
adapter.setInstituteStudent(false);
adapter.setCourses(courses);
}
private void renderInstitute(Institute institute) {
getSupportActionBar().setTitle("Select Batches");
TextView title = (TextView) findViewById(R.id.tv_select_enrollment);
title.setText("Select your batches at " + institute.getName());
adapter.setInstituteStudent(true);
adapter.setBatches(institute.getBatches());
// Save institute name
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putString("institute_name", institute.getName());
editor.commit();
}
public void onButtonClick(View view) {
findViewById(R.id.pb_loading).setVisibility(View.VISIBLE);
findViewById(R.id.tv_error).setVisibility(View.GONE);
findViewById(R.id.ll_content_area).setVisibility(View.GONE);
if(adapter.isInstituteStudent()) {
ArrayList<Batch> batches = adapter.getBatches();
ArrayList<Integer> batchIds = new ArrayList<>();
for(Batch batch: batches) {
if(batch.isPreselect())
batchIds.add(batch.getId());
}
GeneralApiService.addBatches(this, batchIds);
} else {
ArrayList<CourseSlug> courses = adapter.getCourses();
ArrayList<String> courseSlgus = new ArrayList<>();
for(CourseSlug course: courses) {
if(course.isPreselect())
courseSlgus.add(course.getSlug());
}
GeneralApiService.addCourses(this, courseSlgus);
}
new SavePlatformNamesTask().execute();
}
Create a method in your activity like,
public void updateUI(boolean isChecked){
if(isChecked){
// code to enable button
}else
// code to disable button
}
and then keep tracking if at least one item is selected in your Recycler View and keep a boolean(say isItemSelected) value for that. On selecting/deselecting any of the item in adapter, call the method in your activity along with flag isItemSelected.

Categories

Resources