I have a recycler view with check box in the each card in the view. I want to unchek all the other checkboxes when i clicks on a particular check box in the view(Condition can be like card contains an odd one etc). How can i do that? My adapter 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);
}
}
In my Courseslug class, there is a param called isTrue(); if ,courseSlug.isTrue()==true; then which card's check box is satisfying my condition, it gets checked and other unchecked/checked boxes gets unchecked. This is what i want done.
public class CourseSlug {
String name;
String slug;
boolean preselect;
boolean istrue;
public boolean isTrue() {
return istrue;
}
public void setisTrue(boolean isTrue) {
this.isTrue = istrue;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public boolean isPreselect() {
return preselect;
}
public void setPreselect(boolean preselect) {
this.preselect = preselect;
}}
Since the views are not necessarily visible, you need to keep a boolean state variable in your adapter. Toggle the variable when the user clicks the "master" checkbox. Then use this variable in onBindViewHolder() to set the checked state of the checkbox in each row.
I have edited your onBindViewHolder method. Hope this is helpful :)
private SparseArray<SparseBooleanArray> sparseArray = new SparseArray<>();
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final CourseSlug course = courses.get(position);
holder.enrolment.setText(course.getName());
holder.selectEnrollment.setChecked(course.isPreselect());
holder.selectEnrollment.setId(position);
holder.selectEnrollment.setChecked(false);
if (sparseArray.get(holder.selectEnrollment.getId()) != null) {
boolean isChecked = sparseArray.get(holder.selectEnrollment.getId()).get(holder.selectEnrollment.getId());
holder.selectEnrollment.setChecked(isChecked);
}
holder.selectEnrollment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sparseArray.clear();
SparseBooleanArray checkedPosition = new SparseBooleanArray();
checkedPosition.put(v.getId(), true);
sparseArray.put(tagId, checkedPosition);
notifySetDataChanged();
}
});
}
Related
I am developing the Workout log app now.
Two items (routine and routine detail) are expressed using one recycler view and adapter.
If i click the Add Routine button, a routine item is added, and the routine basically has one routine detail item.
Routine items have buttons to add or delete routine detail items.
I used DiffUtil to update the item.
In areItemsTheSame(), I used hashCode to compare oldList and newList.
However, there is a problem of unknown cause when adding or deleting items. (Not an error).
If i click the delete button after adding the routine item and the detail item, it works well at first.
The routine detail buttons of the next routine item cannot be added or deleted unless the delete button of the previous routine item is pressed.
If the delete button of the previous routine item is pressed and then the button of the next item is pressed, the addition or deletion is performed.
Why is this?
This happens when you use hashCode comparison.
However, with equals() this does not happen and works fine.
Instead, every time an item is added or deleted, the entire item is updated with blinking.
How did I have to define the DiffUtil class?
CODE
RoutineModel.java
public class RoutineModel {
private ArrayList<RoutineDetailModel> routineDetailList;
private String routine;
public RoutineModel(String routine) {
this.routine = routine;
}
public void addDetail(RoutineDetailModel item) {
if(routineDetailList == null) {
routineDetailList = new ArrayList<>();
}
this.routineDetailList.add(item);
}
public ArrayList<RoutineDetailModel> getDetailItemList() {
return routineDetailList;
}
public int getDetailItemSize() {
return routineDetailList.size();
}
public String getRoutine() {
return routine;
}
public void removeDetails(int index) throws Exception {
this.routineDetailList.remove(index);
}
#Override
public int hashCode() {
return Objects.hash(routineDetailList, routine);
}
#Override
public boolean equals(#Nullable Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
RoutineModel that = (RoutineModel) obj;
return Objects.equals(routine, that.routine) && Objects.equals(routineDetailList, that.routineDetailList);
}
}
RoutineAdapter.java
public class RoutineAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
final static int TYPE_ROUTINE = 1;
final static int TYPE_ROUTINE_DETAIL = 2;
private Context context;
private List<Object> mItems = new ArrayList<>();
OnRoutineItemClickListener listener;
public void updateRoutineList(List<Object> newRoutineList) {
final RoutineDiffUtil diffCallback = new RoutineDiffUtil(this.mItems, newRoutineList);
final DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);
this.mItems.clear();
this.mItems.addAll(newRoutineList);
diffResult.dispatchUpdatesTo(this);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
if (viewType == TYPE_ROUTINE) {
View itemView = LayoutInflater.from(context).inflate(R.layout.routine_item, parent, false);
return new RoutineViewHolder(itemView);
}
View itemView = LayoutInflater.from(context).inflate(R.layout.routine_detail_item, parent, false);
return new RoutineDetailViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
Object object = mItems.get(position);
if(object instanceof RoutineModel) {
setRoutineData((RoutineViewHolder) holder, (RoutineModel) object, position);
}
else if(object instanceof RoutineDetailModel) {
}
}
private void setRoutineData(RoutineViewHolder holder, RoutineModel routineItem, int position){
holder.routine.setText(routineItem.getRoutine());
holder.addSet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null) listener.OnAddBtnClick(position);
}
});
holder.deleteSet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null) listener.OnDeleteBtnClick(position);
}
});
}
public Object getRoutineItem(int position) {
if(mItems == null || position < 0 || position >= mItems.size())
return null;
return mItems.get(position);
}
#Override
public int getItemCount() {
if(mItems == null)
return -1;
return mItems.size();
}
#Override
public int getItemViewType(int position) {
Object obj = mItems.get(position);
if(obj instanceof RoutineModel) {
return TYPE_ROUTINE;
}
return TYPE_ROUTINE_DETAIL;
}
// detail add,delete click interface
public interface OnRoutineItemClickListener {
public void OnAddBtnClick(int curRoutinePos);
public void OnDeleteBtnClick(int curRoutinePos);
}
public void setOnRoutineClickListener(OnRoutineItemClickListener listener) {
this.listener = listener;
}
public class RoutineViewHolder extends RecyclerView.ViewHolder {
public TextView routine;
public Button addSet;
public Button deleteSet;
public RoutineViewHolder(#NonNull View itemView) {
super(itemView);
routine = itemView.findViewById(R.id.routine);
addSet = itemView.findViewById(R.id.add_set);
deleteSet = itemView.findViewById(R.id.delete_set);
}
}
public class RoutineDetailViewHolder extends RecyclerView.ViewHolder {
public TextView set;
public TextView weight;
public RoutineDetailViewHolder(#NonNull View itemView) {
super(itemView);
set = itemView.findViewById(R.id.set);
weight = itemView.findViewById(R.id.weight);
}
}
}
RoutineDiffUtil.java
public class RoutineDiffUtil extends DiffUtil.Callback {
private List<Object> oldRoutineList;
private List<Object> newRoutineList;
public RoutineDiffUtil(List<Object> oldRoutineList) {
this.oldRoutineList = oldRoutineList;
newRoutineList = new ArrayList<>();
}
public RoutineDiffUtil(List<Object> oldRoutineList, List<Object> newRoutineList) {
this.oldRoutineList = oldRoutineList;
this.newRoutineList = newRoutineList;
}
#Override
public int getOldListSize() {
return oldRoutineList.size();
}
#Override
public int getNewListSize() {
return newRoutineList.size();
}
#Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
// boolean result = oldRoutineList.equals(newRoutineList); // work well
boolean result = oldRoutineList.get(oldItemPosition).hashCode() == newRoutineList.get(newItemPosition).hashCode();
return result;
}
#Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
return oldRoutineList.get(oldItemPosition).equals(newRoutineList.get(newItemPosition));
}
}
MainActivity.java
public class WriteRoutineActivity extends AppCompatActivity {
Button add_routine_btn;
TextView title;
RecyclerView routine_rv;
LinearLayoutManager routineLayoutManger;
RoutineAdapter routineAdapter;
List<RoutineModel> items;
List<String> titleData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write_routine);
initViews();
setPageTitle(getIntent());
setRoutineRecyclerview();
items = new ArrayList<>();
routineAdapter = new RoutineAdapter();
routine_rv.setAdapter(routineAdapter);
add_routine_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WorkoutListDialogFragment routineDialog = new WorkoutListDialogFragment();
routineDialog.show(getSupportFragmentManager(), "RoutineListDialog");
}
});
routineAdapter.setOnRoutineClickListener(new RoutineAdapter.OnRoutineItemClickListener() {
#Override
public void OnAddBtnClick(int routinePos) {
Object obj = routineAdapter.getRoutineItem(routinePos);
if(obj instanceof RoutineModel) {
RoutineModel item = (RoutineModel) obj;
item.addDetail(new RoutineDetailModel());
routineAdapter.updateRoutineList(getDataToBeDisplayed());
}
}
#Override
public void OnDeleteBtnClick(int routinePos) {
Object item = routineAdapter.getRoutineItem(routinePos);
if(item instanceof RoutineModel) {
RoutineModel routineModel = (RoutineModel) item;
if(routineModel.getDetailItemSize() > 1) {
try {
routineModel.removeDetails(routineModel.getDetailItemSize() - 1);
} catch (Exception e) {
e.printStackTrace();
}
}
else { // if delete item exists only one
items.remove(routineModel);
}
routineAdapter.updateRoutineList(getDataToBeDisplayed());
}
}
});
}
public void addRoutine(String routine) {
RoutineModel routineModel = new RoutineModel(routine);
RoutineDetailModel routineDetailModel = new RoutineDetailModel();
routineModel.addDetail(routineDetailModel);
items.add(routineModel);
routineAdapter.updateRoutineList(getDataToBeDisplayed());
}
private List<Object> getDataToBeDisplayed() {
List<Object> mixedList = new ArrayList<>();
for(RoutineModel rm: items){
mixedList.add(rm);
if(rm.getDetailItemList() != null && rm.getDetailItemSize() > 0){
for(RoutineDetailModel rmdetilas: rm.getDetailItemList()){
mixedList.add(rmdetilas);
}
}
}
return mixedList;
}
}
I have a RecyclerView filled with elements of the "Event" class. The class has parameters such as Date and Importance.
Now all Events in RecyclerView are displayed just like that.
I want to show Events by Date separately and also want to show Events by importance separately. I'll attach a picture to show what I mean.
I read that to do separation, for example, by dates, you need to make a separate adapter and viewholder. Question - if I want to split the same data array by importance, do I need to create another adapter?
And let's say I want to choose a grouping method. How can I do this and where?
My First RecyclerViewAdapter of Event
public class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventViewHolder> {
private static final String TAG = "myLogs";
private List<Event> mEventList;
final SparseBooleanArray selectedItems = new SparseBooleanArray();
private int currentSelectedPos;
public List<Event> getEvents(){
return mEventList;
}
private EventAdapterListener itemClickListener;
public interface EventAdapterListener {
void onItemClick(int position);
void onItemLongClick(int position);
}
public void setListener(EventAdapterListener listener){
itemClickListener = listener;
}
private OnItemCheckedListener OnItemChecked;
public interface OnItemCheckedListener {
void onItemChecked(int position, boolean isImportant);
}
public void setOnItemCheckedListener (OnItemCheckedListener listener){
OnItemChecked = listener;
}
public static class EventViewHolder extends RecyclerView.ViewHolder{
public TextView TVtitle;
public TextView TVcomment;
public CheckBox CBimportance;
public TextView TVdate;
//public EventViewHolder(#NonNull View itemView, final EventAdapterListener listener) {
public EventViewHolder(#NonNull View itemView) {
super(itemView);
TVtitle = itemView.findViewById(R.id.tvTitle);
TVcomment = itemView.findViewById(R.id.tvComment);
CBimportance = itemView.findViewById(R.id.cbIconImportant);
TVdate = itemView.findViewById(R.id.tvDate);
}
}
public void removeItem(int position) {
mEventList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mEventList.size());
}
private static DateFormatSymbols myDateFormatSymbols = new DateFormatSymbols(){
#Override
public String[] getMonths() {
return new String[]{"января", "февраля", "марта", "апреля", "мая", "июня",
"июля", "августа", "сентября", "октября", "ноября", "декабря"};
}
};
public EventAdapter(ArrayList<Event> listEvent){
mEventList = listEvent;
}
#NonNull
#Override
public EventViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_cardview, parent, false);
//LayoutInflater inflater = LayoutInflater.from(parent.getContext());
//if (viewType == Constants.VIEWTYPE_GROUP){
//ViewGroup group = (ViewGroup) inflater.inflate(R.layout.group_layout, parent, false);
//GroupViewHolder
//}
return new EventViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull EventViewHolder holder, final int position) {
final Event item = mEventList.get(position);
holder.TVtitle.setText(item.getName());
holder.TVcomment.setText(item.getComment());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMMM", myDateFormatSymbols);
holder.TVdate.setText(simpleDateFormat.format(item.getDate()));
holder.CBimportance.setOnCheckedChangeListener(null);
holder.CBimportance.setChecked(item.getImportant());
holder.CBimportance.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
item.IsImportant = b;
OnItemChecked.onItemChecked(position, b);
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (selectedItems.size() > 0 && itemClickListener != null){
itemClickListener.onItemClick(position);
}
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
if (itemClickListener != null){
itemClickListener.onItemLongClick(position);
}
return true;
}
});
if (currentSelectedPos == position) currentSelectedPos = -1;
}
#Override
public int getItemCount() {
return mEventList.size();
}
void deleteEvents(){
List<Event> events = new ArrayList<>();
for (Event event : mEventList){
if (event.getSelected())
events.add(event);
}
mEventList.removeAll(events);
notifyDataSetChanged();
currentSelectedPos = -1;
}
void toggleSelection(int position) {
currentSelectedPos = position;
if (selectedItems.get(position)) {
selectedItems.delete(position);
mEventList.get(position).setSelected(false);
} else {
selectedItems.put(position, true);
mEventList.get(position).setSelected(true);
}
notifyItemChanged(position);
}}
I am using a RecyclerView and an adapter to display the data of an array of Event objects. In RecyclerView, I use a CheckBox for one of the object's parameters. How can I save it?
For the rest I use SharedPreferences, but here I don't know how to apply it in my Activity.
Here's my class Event:
public class Event implements Serializable {
public String Name;
public Long Date;
public String Comment;
public String Type;
public String Notify;
public Boolean IsComplete;
public Boolean IsImportant;
Event()
{
Name = "Событие";
Date = MaterialDatePicker.todayInUtcMilliseconds();
Comment = "Comment";
Type = "Material";
Notify = "Не напоминать";
IsComplete = false;
IsImportant = false;
}
Event(String name, Long date, String comment, String type, String notify, Boolean iscomplete, Boolean isimportant)
{
Name = name;
Date = date;
Comment = comment;
Type = type;
Notify = notify;
IsComplete = iscomplete;
IsImportant = isimportant;
}
public String getName() {
return Name;
}
public Long getDate() {
return Date;
}
public String getComment() {
return Comment;
}
public String getType() {
return Type;
}
public String getNotify() {
return Notify;
}
public Boolean getComplete() {
return IsComplete;
}
public Boolean getImportant() {
return IsImportant;
}
}
And my Recycler View and Adapter:
public class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventViewHolder> {
private static final String TAG = "myLogs";
private ArrayList<Event> mEventList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public static class EventViewHolder extends RecyclerView.ViewHolder{
public TextView TVtitle;
public TextView TVcomment;
public CheckBox CBimportance;
public EventViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
TVtitle = itemView.findViewById(R.id.tv1);
TVcomment = itemView.findViewById(R.id.tv2);
CBimportance = itemView.findViewById(R.id.iconImportant);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
if (listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
public EventAdapter(ArrayList<Event> listEvent){
mEventList = listEvent;}
#NonNull
#Override
public EventViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_cardview, parent, false);
EventViewHolder evh = new EventViewHolder(v, mListener);
return evh;
}
#Override
public void onBindViewHolder(#NonNull EventViewHolder holder, final int position) {
final Event item = mEventList.get(position);
holder.TVtitle.setText(item.getName());
holder.TVcomment.setText(item.getComment());
holder.CBimportance.setOnCheckedChangeListener(null);
holder.CBimportance.setChecked(item.getImportant());
holder.CBimportance.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
item.IsImportant = b;
if (b){
Log.d(TAG, String.valueOf(position) + " IMPORTANT");
}
else{
Log.d(TAG, String.valueOf(position) + " NON IMPORTANT");
}
}
});
}
#Override
public int getItemCount() {
return mEventList.size();
}
}
For example, for ItemClick and changes saving in my Activity I use onItemClick:
adapterEvent.setOnItemClickListener(new EventAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
eventsProcess.remove(position);
adapterEvent.notifyItemRemoved(position);
write(getContext(), eventsProcess, PROCESSED_EVENTS);
}
});
public static void write(Context context, ArrayList<Event> events, String Key)
{
Gson gson = new Gson();
String jsonString = gson.toJson(events);
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = pref.edit();
editor.putString(Key, jsonString);
editor.apply();
}
You should be able to do this exactly how you handle the 'OnItemClick'. I made some changes in your adapter to add a new interface OnItemCheckedListener and then handle the checkbox checkedChanged events using this listener. (Instead of just logging it like you did).
public class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventViewHolder> {
private static final String TAG = "myLogs";
private ArrayList<Event> mEventList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
private OnItemCheckedListener mOnItemChecked;
public interface OnItemCheckedListener {
void onItemChecked (int position, boolean isImportant);
}
public void setOnItemCheckedListener (OnItemCheckedListener listener) {
mOnItemChecked = listener;
}
public static class EventViewHolder extends RecyclerView.ViewHolder{
public TextView TVtitle;
public TextView TVcomment;
public CheckBox CBimportance;
public EventViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
TVtitle = itemView.findViewById(R.id.tv1);
TVcomment = itemView.findViewById(R.id.tv2);
CBimportance = itemView.findViewById(R.id.iconImportant);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
if (listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
public EventAdapter(ArrayList<Event> listEvent){
mEventList = listEvent;
}
#NonNull
#Override
public EventViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_cardview, parent, false);
EventViewHolder evh = new EventViewHolder(v, mListener);
return evh;
}
#Override
public void onBindViewHolder(#NonNull EventViewHolder holder, final int position) {
final Event item = mEventList.get(position);
holder.TVtitle.setText(item.getName());
holder.TVcomment.setText(item.getComment());
holder.CBimportance.setOnCheckedChangeListener(null);
holder.CBimportance.setChecked(item.getImportant());
holder.CBimportance.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
item.IsImportant = b;
if (b) {
Log.d(TAG, String.valueOf(position) + " IMPORTANT");
}
else{
Log.d(TAG, String.valueOf(position) + " NON IMPORTANT");
}
mOnItemChecked.onItemChecked(position, b)
}
});
}
#Override
public int getItemCount() {
return mEventList.size();
}
}
Now, From your activity just set the OnItemCheckedListener of the EventAdapter.
adapterEvent.setOnItemCheckedListener(new EventAdapter.OnItemCheckedListener {
#Override
public void onItemChecked (int position, boolean isImportant) {
// TODO:
// whatever you want to do with the isImportant data
}
});
I am learning to use FastAdapter with Realm. Here is my model and this is how I implement OnClick in a Fragment:
fastAdapter.withOnClickListener(new FastAdapter.OnClickListener<ProductsModel>() {
#Override
public boolean onClick(View v, IAdapter<ProductsModel> adapter, ProductsModel item, int position) {
Toast.makeText(getActivity(), "got it", Toast.LENGTH_SHORT).show();
return false;
}
});
But I don't get the Toast appearing. Can anybody please tell me what am I missing?
Update: Here is my model
public class ProductsModel extends RealmObject implements IItem<ProductsModel, ProductsModel.ViewHolder>{
#PrimaryKey
private String code;
private String name, generic, packSize;
private int quantity, status;
//variables needed for adapter
protected boolean isSelected = false; // defines if the item is selected
#Ignore
protected Object tag;// defines if this item is isSelectable
#Ignore
protected boolean isSelectable = true;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPackSize() {
return packSize;
}
public void setPackSize(String packSize) {
this.packSize = packSize;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getGeneric() {
return generic;
}
public void setGeneric(String generic) {
this.generic = generic;
}
#Override
public Object getTag() {
return tag;
}
#Override
public ProductsModel withTag(Object tag) {
this.tag = tag;
return this;
}
#Override
public boolean isEnabled() {
return false;
}
#Override
public ProductsModel withEnabled(boolean enabled) {
return null;
}
#Override
public boolean isSelected() {
return isSelected;
}
#Override
public ProductsModel withSetSelected(boolean selected) {
return null;
}
#Override
public boolean isSelectable() {
return isSelectable;
}
#Override
public ProductsModel withSelectable(boolean selectable) {
this.isSelectable = selectable;
return this;
}
#Override
public int getType() {
return R.id.pwdsList;
}
#Override
public int getLayoutRes() {
return R.layout.item_product;
}
#Override
public View generateView(Context ctx) {
ViewHolder viewHolder = getViewHolder(LayoutInflater.from(ctx).inflate(getLayoutRes(), null, false));
bindView(viewHolder, Collections.EMPTY_LIST);
return viewHolder.itemView;
}
#Override
public View generateView(Context ctx, ViewGroup parent) {
ViewHolder viewHolder = getViewHolder(LayoutInflater.from(ctx).inflate(getLayoutRes(), parent, false));
bindView(viewHolder, Collections.EMPTY_LIST);
return null;
}
private ViewHolder getViewHolder(View view) {
return new ViewHolder(view);
}
#Override
public ViewHolder getViewHolder(ViewGroup parent) {
return getViewHolder(LayoutInflater.from(parent.getContext()).inflate(getLayoutRes(), parent, false));
}
#Override
public void bindView(ViewHolder holder, List<Object> payloads) {
holder.name.setText(name + " " + packSize + " (" + quantity + ")");
holder.generic.setText(generic);
holder.itemView.setSelected(isSelected());
}
#Override
public void unbindView(ViewHolder holder) {
holder.name.setText(null);
holder.generic.setText(null);
}
#Override
public boolean equals(int id) {
return false;
}
#Override
public ProductsModel withIdentifier(long identifier) {
return null;
}
#Override
public long getIdentifier() {
return 0;
}
static class ViewHolder extends RecyclerView.ViewHolder{
ATextView name, generic;
public ViewHolder(View itemView) {
super(itemView);
name = (ATextView) itemView.findViewById(R.id.name);
generic = (ATextView) itemView.findViewById(R.id.generic);
}
}
}
Your item is not enabled which results in the click event not being forwarded. Just change your code to return isEnabled=true
#Override
public boolean isEnabled() {
return true;
}
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.