My Code is:
JSONArray jsonArray=new JSONArray(response);
if(jsonArray.length()==0){
Toast.makeText(context,"No Data",Toast.LENGTH_SHORT).show();
}else {
for (int i = 0; i < jsonArray.length(); i++) {
innerListData = new TakeAttendanceModel();
innerListData = ((TakeAttendanceModel) JSonUtil.jsonToObject(jsonArray.getString(i), TakeAttendanceModel.class));
innerListData.status = "P";
innerListData.attendanceDate = DateTimeUtils.getDate();
attenList.add(innerListData);
}
submitAtten=(Button)rootView.findViewById(R.id.takeAttendanceSubmit);
submitAtten.setVisibility(View.VISIBLE);
}
Log.d("Responsse : ", response);
}
takeAttendanceAdapter = new TakeAttendanceAdapter(context,attenList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(context);
recyclerViewAttendanceList.setLayoutManager(mLayoutManager);
recyclerViewAttendanceList.setItemAnimator(new DefaultItemAnimator());
recyclerViewAttendanceList.setAdapter(takeAttendanceAdapter);
takeAttendanceAdapter.notifyDataSetChanged();
My Adapter code is:
private List<TakeAttendanceModel> list;
public TakeAttendanceAdapter(Context context, List<TakeAttendanceModel> list) {
this.context = context;
this.list = list;
}
#Override
public AttendanceListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View convertview = LayoutInflater.from(parent.getContext())
.inflate(R.layout.inner_list_attendance, parent, false);
return new AttendanceListViewHolder(convertview);
}
#Override
public void onBindViewHolder(final AttendanceListViewHolder holder, final int position) {
holder.textViewStudentName.setText(list.get(position).studFullName);
holder.textViewStudentRollNumber.setText(list.get(position).primaryKey);
holder.texViewStudentPreFix.setText(list.get(position).prefix);
holder.SSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
//final LinkedList<String> innerLinklist=new LinkedList<>();
if (isChecked) {
/*innerLinklist.add(list.get(position).primaryKey);
innerLinklist.add(list.get(position).studFullName);
innerLinklist.add(list.get(position).status="P");*/
// linkedList.add(innerLinklist);
//Log.v("Attndce Liist After Toggle",linkedList.toString());
list.get(position).status="P";
} else {
/*innerLinklist.add(list.get(position).primaryKey);
innerLinklist.add(list.get(position).studFullName);
innerLinklist.add(list.get(position).status="A");*/
// linkedList.add(innerLinklist);
//Log.v("Attndce Liist After Toggle",linkedList.toString());
list.get(position).status="A";
}
Log.v("Attndce Inner",list.toString());
//DataManager.factory().linkedList.add(innerLinklist);
//Log.v("Attndce Full Linklist",DataManager.factory().linkedList.toString());
}
});
//Log.v("Attndce Liist After Toggle",DataManager.factory().linkedList.toString());
}
#Override
public int getItemCount() {
return list.size();
}
public class AttendanceListViewHolder extends RecyclerView.ViewHolder {
/*public ImageView imageViewProfilePic;*/
public TextView textViewStudentName, textViewStudentRollNumber,texViewStudentPreFix;
public SwitchCompat SSwitch;
public AttendanceListViewHolder(View convertview) {
super(convertview);
texViewStudentPreFix=(TextView)convertview.findViewById(R.id.textAttendanceStudentPrfix) ;
textViewStudentName = (TextView) convertview.findViewById(R.id.textViewAttendanceStudentName);
textViewStudentRollNumber = (TextView) convertview.findViewById(R.id.textViewAttendanceStudentRollno);
SSwitch = (SwitchCompat) convertview.findViewById(R.id.textViewAttendanceSwitch);
}
}
This is My adapter code in which switch is placed.
Actually in RecylerView I place a Switch button and when switch button is on at 0 position then Automatically switch is ON after 9th position.
Please give me a solution.
First things first, make a proper POJO class for your adapter.
never use something like list.get(position).variable instead of this make your variable as private and use setters and getters like list.get(position).getVariable() or list.get(position).setVariable(variable)
Then as you know, since RecyclerView always recycle the views, its advisable to use if followed by else for every UI change. In your case you are just changing the switch condition without resetting it anywhere.
And the most important part, never use the position that is passed as
a paremeter. Instead use the adapter position as I specified in the
solution
Check the updated code below:
#Override
public void onBindViewHolder(final AttendanceListViewHolder holder, final int position) {
final int adapterPosition = holder.getAdapterPosition();
holder.textViewStudentName.setText(list.get(adapterPosition).studFullName);
holder.textViewStudentRollNumber.setText(list.get(adapterPosition).primaryKey);
holder.texViewStudentPreFix.setText(list.get(adapterPosition).prefix);
holder.SSwitch.setSelected(list.get(adapterPosition).getStatus());
holder.SSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
list.get(adapterPosition).setStatus(isChecked);
notifyItemChanged(adapterPosition);
Log.v("Attndce Inner",list.toString());
}
});
}
Update code is:
#Override
public void onBindViewHolder(final AttendanceListViewHolder holder, int position) {
final int adapterPosition = holder.getAdapterPosition();
holder.textViewStudentName.setText(list.get(adapterPosition).studFullName);
holder.textViewStudentRollNumber.setText(list.get(adapterPosition).primaryKey);
holder.texViewStudentPreFix.setText(list.get(adapterPosition).prefix);
holder.SSwitch.setSelected(list.get(adapterPosition).getStatus());
holder.SSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
list.get(adapterPosition).setStatus(isChecked);
notifyItemChanged(adapterPosition);
Log.v("Attndce Inner",list.toString());
//Log.v("Attndce Full Linklist",DataManager.factory().linkedList.toString());
}
});
Model Class is:
public class TakeAttendanceModel {
public String primaryKey;
public String prefix;
public String studFullName;
public String attendanceDate;
public boolean status;
public boolean getStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
Related
I have a RecyclerView which has a checkbox and textview.Numbers 10,20,30,40... till 500 should be shown in textview.The Checked checkboxes should add the numbers in the textview corresponding to the checkbox.For eg. if User checks the value 10 only, the textView would show 10. If user checks 20 as well, then
TextView would show 30 ( 20 +10).
If user uncheck 10 again, the TextView would show 20, and so on.When i click on checkbox some random checkbox is also checked.I tried one solution in stackoverflow. It did not work.I am stuck with this.Please help me..Here is my code:
RecyclerAdapter.java:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerHolder>
{
#NonNull
#Override
public RecyclerHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new RecyclerHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_lyt,parent,false));
}
#Override
public void onBindViewHolder(#NonNull RecyclerHolder holder, final int position) {
holder.number.setText(Integer.toString((Integer) alldata.get(position)));
final String text=holder.number.getText().toString();
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.e("Checked","Checked");
if(checkeddata!=null)
{
if (checkeddata.size()==0)
{
checkeddata.add(text);
}
else {
if(checkeddata.contains(text))
{
checkeddata.remove(text);
}
else {
checkeddata.add(text);
}
}
Iterator iterator=checkeddata.iterator();
int sumnumber=0;
while (iterator.hasNext())
{
sumnumber= sumnumber+Integer.parseInt((String) iterator.next());
}
sum.setText(Integer.toString(sumnumber));
}
}
});
}
#Override
public int getItemCount() {
return alldata.size();
}
public class RecyclerHolder extends RecyclerView.ViewHolder
{
TextView number;
CheckBox checkBox;
public RecyclerHolder(View itemView) {
super(itemView);
number=itemView.findViewById(R.id.number);
checkBox=itemView.findViewById(R.id.check);
}
}
}
public void data()
{
int g=1;
for(int i=10;i<=500;i++)
{
if((i/10)==g)
{
g=g+1;
alldata.add(i);
}
}
}
recycler_lyt.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:id="#+id/number"
android:textSize="20sp"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/check"
android:checked="false"
app:layout_constraintRight_toRightOf="parent"/>
</android.support.constraint.ConstraintLayout>
It's normal. You are not setting your checkbox selected or not. You are selecting one and View holder keeps it selected
You may look at my example. You can do something like that:
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final Data data = myItems.get(position);
//in some cases, it will prevent unwanted situations
holder.checkBox.setOnCheckedChangeListener(null);
//if true, your checkbox will be selected, else unselected
holder.checkBox.setChecked(data.isSelected());
holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//set your object's last status
data.setSelected(isChecked);
}
});
}
inside your onBindViewHolder you have to set your checkbox either checked or unchecked.
if true, your checkbox will be selected, else unselected
holder.checkBox.setChecked(boolean);
You must store your checkbox state. You can do that in your model, for example:
class Model {
String title;
boolean checked;
}
Next you must pass List of Model items to your adapter and check/uncheck checkbox determined by your model.
if (listOfItems.get(position).checked) {
viewHolder.checkbox.setChecked(true);
} else {
viewHolder.checkbox.setChecked(false);
}
Remember that you always need to manage opposite state of views (like checkbox or visibility of view) in adapter.
Try This:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerHolder>
{
private OnClickListener onClickListener;
private int sum =0;
#NonNull
#Override
public RecyclerHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new RecyclerHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_lyt,parent,false));
}
#Override
public void onBindViewHolder(#NonNull RecyclerHolder holder, final int position) {
holder.number.setText(Integer.toString((Integer) alldata.get(position)));
final String text=holder.number.getText().toString();
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
sum += Integer.parseInt(holder.number.getText().toString());
}else{
sum -= Integer.parseInt(holder.number.getText().toString());
}
if (onClickListener != null) {
onClickListener.onItemClick(sum);
}
});
}
#Override
public int getItemCount() {
return alldata.size();
}
public class RecyclerHolder extends RecyclerView.ViewHolder
{
TextView number;
CheckBox checkBox;
public RecyclerHolder(View itemView) {
super(itemView);
number=itemView.findViewById(R.id.number);
checkBox=itemView.findViewById(R.id.check);
}
}
public void setOnClickListener(OnClickListener onClickListener) {
this.onClickListener = onClickListener;
}
public interface OnClickListener {
void onItemClick(int sum);
}
}
Now In activity use adapter instance like this:
private RecyclerAdapter adapter;
...
...
cardAdapter.setOnClickListener(new CardAdapter.OnClickListener() {
#Override
public void onItemClick(int sum) {
txtSum.setText(String.valueOf(sum));
});
You need to have a field (like "isSelected") in your model class so that all the checked entries can be tracked.you can try following:
checkboxRecyclerView
Basically, RecyclerView recycles the view so you need a model to store the state of the checkbox.
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerHolder> {
private List<Model> alldata = new ArrayList<>();
#NonNull
#Override
public RecyclerHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new RecyclerHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_lyt, parent, false));
}
#Override
public void onBindViewHolder(#NonNull RecyclerHolder holder, final int position) {
final Model model = alldata.get(position);
holder.number.setText(String.valueOf(model.value));
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
model.setChecked(isChecked); // Saves the state of the checkbox.
if (checkeddata != null) {
if (checkeddata.size() == 0) {
checkeddata.add(text);
} else {
if (checkeddata.contains(model.getValue())) {
checkeddata.remove(model.getValue());
} else {
checkeddata.add(model.getValue());
}
}
Iterator iterator = checkeddata.iterator();
int sumnumber = 0;
while (iterator.hasNext()) {
sumnumber = sumnumber + Integer.parseInt((String) iterator.next());
}
sum.setText(Integer.toString(sumnumber));
}
}
});
holder.checkBox.setChecked(model.isChecked()); // Retrieves the state of your checkbox.
}
#Override
public int getItemCount() {
return alldata.size();
}
public class RecyclerHolder extends RecyclerView.ViewHolder {
TextView number;
CheckBox checkBox;
public RecyclerHolder(View itemView) {
super(itemView);
number = itemView.findViewById(R.id.number);
checkBox = itemView.findViewById(R.id.check);
}
}
public void data() {
int g = 1;
for (int i = 10; i <= 500; i++) {
if ((i / 10) == g) {
g = g + 1;
alldata.add(new Model(i));
}
}
}
private class Model {
private int value;
private boolean checked = false;
Model(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
}
}
If you made the necessary changes to store the state of the checkbox, then:
in onBindViewHolder() after final String text=holder.number.getText().toString(); add this:
holder.checkBox.setOnCheckedChangeListener(null);
holder.checkBox.setChecked(-- stored value --);
and then add the listener for the checkbox.
I have a check box in RecyclerView Adapter's View Item.
When scrolling, some check boxes are getting checked and some are getting unchecked.
I have taken help from this and this
But I am unable to find the exact solution to this.
Here is my code
public class AllContactsAdapter extends RecyclerView.Adapter<AllContactsAdapter.ViewHolder> {
private Context context;
private ArrayList<PhoneContactsModel> listOfContacts = new ArrayList<>();
PhoneContactsModel phoneContactsModel;
private ArrayList<PhoneContactsModel> copyOfListOfContacts = new ArrayList<>();
public AllContactsAdapter(Context context, ArrayList<PhoneContactsModel> listOfContacts) {
this.context = context;
this.listOfContacts = listOfContacts;
// copyOfListOfContacts.addAll(listOfContacts);
}
#Override
public AllContactsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.
adapter_load_allusers_contacts_listitem, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final AllContactsAdapter.ViewHolder holder, final int position) {
Log.d("tag", "adapter========3");
phoneContactsModel = listOfContacts.get(position);
holder.name.setText(phoneContactsModel.getContactName());
holder.phoneNumber.setText(phoneContactsModel.getContactNumber());
holder.checkBox.setSelected(phoneContactsModel.isChecked());
holder.contactLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.checkBox.isChecked()) {
phoneContactsModel.setChecked(false);
holder.checkBox.setChecked(false);
copyOfListOfContacts.remove(listOfContacts.get(position));
} else {
phoneContactsModel.setChecked(true);
holder.checkBox.setChecked(true);
copyOfListOfContacts.add(listOfContacts.get(position));
}
}
});
}
#Override
public int getItemCount() {
return listOfContacts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView name, phoneNumber;
private CheckBox checkBox;
private LinearLayout contactLayout;
public ViewHolder(View view) {
super(view);
name = view.findViewById(R.id.contactNameId);
phoneNumber = view.findViewById(R.id.contactNumberId);
checkBox = view.findViewById(R.id.checkBoxId);
contactLayout = view.findViewById(R.id.contactLayoutId);
}
}
}
For example, I have checked 1,2,3 items in list. When I scrolled down and come up , then 13 is checked and 2 is unchecked along with other some items.Please help me.
Any solution is appreciated.
A simple way arround is do not use OnCheckedChangeListener just set OnClickListener on Check box . Move checkBox onclick inside ViewHolder class.
public class ViewHolder1 extends RecyclerView.ViewHolder implements View.OnClickListener {
CheckBox checkBox;
public ViewHolder1(View itemView) {
super(itemView);
checkBox = (TextView) itemView.findViewById(R.id.checkBox);
checkBox.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(getAdapterPosition()!=-1) {
phoneContactsModel.get(getAdapterPosition()).setChecked(!phoneContactsModel.get(getAdapterPosition()).isChecked());
notifyItemChanged(getAdapterPosition());
}
}
}
And
public void onBindViewHolder(final AllContactsAdapter.ViewHolder holder, final int position) {
holder.checkBox.setChecked(phoneContactsModel.isChecked());
}
notify your adapter.
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
phoneContactsModel.setChecked(b);
//notifyItemChanged(position);(if you want to notify change in single item)
//or
//notifyDataSetChanged();(if you want to notify change in all)
}
});
no need to use this line of code twice
holder.checkBox.setSelected(phoneContactsModel.isChecked());
//this section seems buggy i assume you want to add the item to the list when ever the check box is checked and remove it from the list when ever the check box is unchecked.
holder.contactLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (phoneContactsModel.isChecked()) {
holder.checkBox.setSelected(false);
copyOfListOfContacts.remove(listOfContacts.get(position));
} else {
holder.checkBox.setSelected(true);
copyOfListOfContacts.add(listOfContacts.get(position));
}
}
}
);
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final PhoneContactsModel phoneContactsModel = listOfContacts.get(position);
holder.name.setText(phoneContactsModel.getContactName());
holder.phoneNumber.setText(phoneContactsModel.getContactNumber());
holder.checkBox.setChecked(/* gets value from the modal */ phoneContactsModel.isChecked());
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean value) {
if (compoundButton.isPressed()) {
holder.checkBox.setChecked(value);
// set the value into the modal.
phoneContactsModel.setChecked(value);
if (value) {
copyOfListOfContacts.remove(phoneContactsModel);
} else {
copyOfListOfContacts.add(phoneContactsModel);
}
}
}
});
}
Change your onBindViewHolder method like this. There won't be any unnecessary checks.
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();
}
});
}
I would like to check the property of one of the items in RecyclerView. To be more specific I want to check if this item is selected.
Firstly I select the item
onView(withId(R.id.list_master))
.perform(
RecyclerViewActions.actionOnItemAtPosition(14, clickAnItem(R.id.layout_menu))
);
Secondly check if the specific item is selected:
onView(allOf(withId(R.id.layout_menu), hasDescendant(withText("SO"))))
.check(matches(isSelected()));
With custom matcher:
private static Matcher<View> isSelected() {
return new TypeSafeMatcher<View>() {
#Override
protected boolean matchesSafely(View item) {
return item.isSelected();
}
#Override
public void describeTo(Description description) {
description.appendText("Selected property");
}
};
Sadly the state of this view is not selected, but UI shows it successfully marked as selected item. Implementation details
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final ViewHolder viewHolder = (ViewHolder) holder;
viewHolder.itemView.setSelected(position == selected);
Check this code I had the same thing want you want check whether the field is selected or not in Recycler View.
public class AutoWithRuleListListAdapter extends RecyclerView.Adapter<AutoWithRuleListListAdapter.ViewHolder> {
private Context context;
private Fragment fragment;
private ArrayList<ObjGetLookupDataResponseIn> lookupData;
public AutoWithRuleListListAdapter(Context context, Fragment fragment, ArrayList<ObjGetLookupDataResponseIn> lookupData) {
this.context = context;
this.fragment = fragment;
this.lookupData = lookupData;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.auto_withdraw_ben_name_list, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, #SuppressLint("RecyclerView") final int position) {
String output = lookupData.get(position).getDisplayName().substring(0, 1).toUpperCase() + lookupData.get(position).getDisplayName().substring(1);
holder.radioBen.setText(output);
holder.radioBen.setOnCheckedChangeListener(null);
holder.radioBen.setChecked(lookupData.get(position).isSelected());
holder.radioBen.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
resetAll();
lookupData.get(position).setSelected(true);
notifyDataSetChanged();
((AutoViewRuleFragment)fragment).ruleName(position);
}
});
}
private void resetAll() {
for (int i=0;i<lookupData.size();i++)
{
lookupData.get(i).setSelected(false);
}
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return lookupData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
RadioButton radioBen;
public ViewHolder(View itemView) {
super(itemView);
radioBen = (RadioButton) itemView.findViewById(R.id.radioReceivesFunds);
radioBen.setTypeface(Utils.gothamMedium);
}
}}
rulename method in my fragment through which i get the position of the view.Add boolean selected in your POJO if this item is selected or not.
Hope this help.Happy Coding.Vote if you find it useful.
I have Recyclerview with Textview and Checkbox. Each item can be hidden or shown. In MainActivity, at run I show only items which are not hidden. But in menu I have an option called - show hidden items. at click I have t oshow also hidden Items, but with gray color.
HOw can I do it? how to reach Recyclerview's single item's properties from MainActivity ?
Here is my code:
RVAdapter
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.DataHolder> {
static String LOG = "RV_LOG";
ArrayList<DataObject> myData;
MainActivity mainActivity;
public static MyClickListener myClickListener;
public class DataHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
CompoundButton.OnCheckedChangeListener {
TextView text;
CheckBox checkBox;
private int position;
public DataHolder(View itemView) {
super(itemView);
text = (TextView) itemView.findViewById(R.id.text);
checkBox = (CheckBox) itemView.findViewById(R.id.checkbox);
checkBox.setOnCheckedChangeListener(this);
}
public void setPosition(int value) {
this.position = value;
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(position, v);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mainActivity.onItemClick(position, buttonView, isChecked);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public RVAdapter(ArrayList<DataObject> myData, MainActivity mainActivity) {
this.myData = myData;
this.mainActivity=mainActivity;
}
#Override
public DataHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_single_item, parent, false);
return new DataHolder(view);
}
#Override
public void onBindViewHolder(final DataHolder holder, final int position) {
holder.text.setText(myData.get(position).getText());
holder.checkBox.setChecked(myData.get(position).getCheck());
if (myData.get(position).getHidden()) {
holder.text.setTextColor(Color.parseColor("#d6d6c2"));
holder.text.setVisibility(View.GONE);
holder.checkBox.setVisibility(View.GONE);
}
holder.setPosition(position);
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public void addItem(DataObject object, int index) {
myData.add(index, object);
notifyItemInserted(index);
}
public void deleteItem(int index) {
myData.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return myData.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
private RecyclerView myRecyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager manager;
private ArrayList<DataObject> data;
String TAG = "MA Tag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data = new ArrayList<DataObject>();
boolean hidden = true;
for (int i = 0; i < 10; i++) {
DataObject object = new DataObject("Item No " + (i + 1), false, hidden);
data.add(i, object);
hidden = !hidden;
}
myRecyclerView = (RecyclerView) findViewById(R.id.rv);
myRecyclerView.setHasFixedSize(true);
adapter = new RVAdapter(data, this);
myRecyclerView.setAdapter(adapter);
manager = new LinearLayoutManager(this);
myRecyclerView.setLayoutManager(manager);
}
public void onItemClick(int position, View view, boolean isChecked) {
switch (view.getId()) {
case R.id.text:
Log.d(TAG, "item is clicked");
break;
case R.id.checkbox:
data.get(position).setCheck(isChecked);
Log.d(TAG, position + " is " + data.get(position).getCheck() + ":" + isChecked);
if (isChecked) {
data.get(position).setCheck(true);
} else {
data.get(position).setCheck(false);
Log.d(TAG, position + " is " + data.get(position).getCheck());
}
break;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
for(int i = data.size()-1; i >=0; i--){
if(data.get(i).getCheck())
((RVAdapter) myRecyclerView.getAdapter()).deleteItem(data.indexOf(data.get(i)));
}
break;
case R.id.show:
Log.d(TAG, "Show");
for(int i = 0; i <data.size(); i++){
if(data.get(i).getHidden()){
Log.d(TAG, data.get(i).getText());
data.get(i).setHidden(false);
}
}
break;
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.layout_menu, menu);
return true;
}
}
UPDATE:
now my RVAdapter looks so:
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.DataHolder> {
static String LOG = "RV_LOG";
ArrayList<DataObject> myData;
MainActivity mainActivity;
public class DataHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
CompoundButton.OnCheckedChangeListener, View.OnLongClickListener {
TextView text;
CheckBox checkBox;
private int position;
public DataHolder(View itemView) {
super(itemView);
text = (TextView) itemView.findViewById(R.id.text);
checkBox = (CheckBox) itemView.findViewById(R.id.checkbox);
checkBox.setOnCheckedChangeListener(this);
text.setOnLongClickListener(this);
}
public void setPosition(int value) {
this.position = value;
}
#Override
public void onClick(View v) {
mainActivity.onItemClick(position, v, true);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mainActivity.onItemClick(position, buttonView, isChecked);
}
#Override
public boolean onLongClick(View v) {
mainActivity.onLongClick(position);
return true;
}
}
public RVAdapter(ArrayList<DataObject> myData, MainActivity mainActivity) {
this.myData = myData;
this.mainActivity=mainActivity;
}
#Override
public DataHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_single_item, parent, false);
return new DataHolder(view);
}
#Override
public void onBindViewHolder(final DataHolder holder, final int position) {
holder.text.setText(myData.get(position).getText());
holder.checkBox.setChecked(myData.get(position).getCheck());
if (myData.get(position).getHidden()) {
holder.text.setVisibility(View.GONE);
holder.checkBox.setVisibility(View.GONE);
}
if(myData.get(position).getWasHidden()){
holder.text.setTextColor(Color.parseColor("#666666"));
}
holder.setPosition(position);
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public void deleteItem(int index) {
myData.remove(index);
notifyItemRemoved(index);
notifyItemRangeChanged(index, myData.size());
}
public void hideItem(int position){
myData.get(position).setHidden(true);
}
public void showItem(int position){
myData.get(position).setHidden(false);
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return myData.size();
}
}
in my Activity I call showItem() method.
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
for(int i = data.size()-1; i >=0; i--){
if(data.get(i).getCheck())
((RVAdapter) myRecyclerView.getAdapter()).deleteItem(data.indexOf(data.get(i)));
}
break;
case R.id.show:
for(int i = 0; i< data.size(); i++) {
if(data.get(i).getHidden())
((RVAdapter) myRecyclerView.getAdapter()).showItem(i);
}
adapter.notifyDataSetChanged();
break;
}
return true;
}
It works a bit wrong: At run every second item is shown(correct, cause every second is not hidden). When I tap on Show, hidden items appear, but first two shown items disappear. when I tap on Show again, they appear. what is wrong here?
Create a method inside the adapter to show the hidden items. Since you have the adapter object inside your Main Activity you can easily call that method from inside your Main Activity. After calling that method, call notifyDataSetChanged() method from your MainActivity itself. notifyDataSetChanged() method will be called by the adapter object.