The first checked item always checked when refresh recyclerview - android

I am using recyclerview with checkbox and search filter. The truble start when i search using filter on recyclerview. for example i have 3 items on recycler view (A,B,C). first time i check item A , and then i search for item B and Check Item B and when i delete the query on search and back to recyclerview (with notifydatasetchanged() to refresh the recyclerview) there is nothing wrong like this
checked
but when i uncheck both items (items A and B), and then i search item c and check the item c, THE FIRST ITEM CHECKED (in here A ) always checked but there is no item A on checkedarraylist
checked but no exist
this is the model for the list in rectclerview
public class herbsModel {
private boolean isSelected;
private String idHerbs,nameHerbs;
public herbsModel(String idHerbs, String nameHerbs) {
this.idHerbs = idHerbs;
this.nameHerbs = nameHerbs;
}
public String getIdHerbs() {
return idHerbs;
}
public String getNameHerbs() {
return nameHerbs;
}
public boolean getSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
this is the search from edittext on mainactivity
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});
private void filter(String s) {
ArrayList<herbsModel> filteredlist = new ArrayList<>();
for (herbsModel item : herbsModels)
{
if(item.getNameHerbs().toLowerCase().contains(s.toLowerCase()))
{
filteredlist.add(item);
}
}
adapter.filterlist(filteredlist);
}
this is how to check the checked items
sb = new StringBuffer();
for (herbsModel h : adapter.checkedHerbs)
{
sb.append(h.getNameHerbs());
sb.append("\n");
}
if (adapter.checkedHerbs.size()>0)
{
Toast.makeText(getActivity(),sb.toString(),Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity(),"Please Check Plants",Toast.LENGTH_SHORT).show();
}
this is the onbindviewholder on adapter that use logic to get checked or unchecked item and store checked item to new array and set checked the items
#Override
public void onBindViewHolder(#NonNull final herbsPredictViewHolder herbsPredictViewHolder, int i) {
final herbsModel detailherbs = herbsModelList.get(i);
herbsPredictViewHolder.name.setText(detailherbs.getNameHerbs());
if(detailherbs.getSelected()==true)
{
herbsPredictViewHolder.checkBox.setChecked(true);
}
else{
herbsPredictViewHolder.checkBox.setChecked(false);
herbsPredictViewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v, int pos) {
CheckBox checkBox = (CheckBox) v;
if (checkBox.isChecked())
{
checkedHerbs.add(herbsModelList.get(pos));
detailherbs.setSelected(true);
}
else if(!checkBox.isChecked())
{
checkedHerbs.remove(herbsModelList.get(pos));
detailherbs.setSelected(false);
}
}
});
}
}
this is the filter function on adapter
public void filterlist (ArrayList<herbsModel> filteredList)
{
herbsModelList =filteredList;
notifyDataSetChanged();
}
The problem is start after check something from searchview and then when recyclerview refresh all of my unchecked items become checked even it is null on checkeditems array list. If i not using the search it works fine

CheckBox checkBox = (CheckBox) v;
if (checkBox.isChecked())
{
checkedHerbs.add(herbsModelList.get(pos));
detailherbs.setSelected(true);
}
else if(!checkBox.isChecked())
{
checkedHerbs.remove(herbsModelList.get(pos));
detailherbs.setSelected(false);
}
I think you need to update this into this
if (!detailherbs.getSelected())
{
checkedHerbs.add(herbsModelList.get(pos));
detailherbs.setSelected(true);
}
else
{
checkedHerbs.remove(herbsModelList.get(pos));
detailherbs.setSelected(false);
}
And update your else code into
else
herbsPredictViewHolder.checkBox.setChecked(false);
herbsPredictViewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v, int pos) {
CheckBox checkBox = (CheckBox) v;
if (checkBox.isChecked())
{
checkedHerbs.add(herbsModelList.get(pos));
detailherbs.setSelected(true);
}
else if(!checkBox.isChecked())
{
checkedHerbs.remove(herbsModelList.get(pos));
detailherbs.setSelected(false);
}
}
});

Related

How to checked specific position checbox in spinner android

I want a spinner with checkbox (custom adapter xml will have one image,textview and checkbox in horizontal line)and whatever checkbox I check it should be checked even when I reopen application. That specific checkbox state should be save and when I open application again that specific checkbox should be checked in spinner that's it.
Description:
I am making a text to speech application and when I click on spinner country name,flag and one checkbox is in one horizontal line and there are almost 50 countries using custom adapter but what I need is whenever user click any country language to translate language application should save that checkbox or that particular position if the user comes again to click on the spinner the user should know which language was selected before by showing checkbox checked that's all.
Thanks looking forward to your answers
This is what I have and want to mark one checkbox checked
try this
//This is how to add in adapter from activity/fragment
CountryAdapter adapter = new CountryAdapter(getApplicationContext(), new CountryAdapter.CountryChangeListener() {
#Override
public void onCountryChange(CountryModel countryModel) {
//persist selected country name in preference
}
});
List<CountryModel> list = loadAllCountries();
adapter.add(list);
String selectedCountry = getSelectedCountry();
if(!TextUtils.isEmpty(selectedCountry)){
adapter.setCountrySelected(selectedCountry);
}
adapter.notifyDataSetChanged();
CountryModel is model class for your adapter.
public class CountryModel {
private String name;
private Drawable countryFlagIcon; //it could be bitmap or resource Id of the icon
/*
isSelected would be true when user selects that particular Country
*/
private boolean isSelected;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Drawable getCountryFlagIcon() {
return countryFlagIcon;
}
public void setCountryFlagIcon(Drawable countryFlagIcon) {
this.countryFlagIcon = countryFlagIcon;
}
public boolean isSelected() {
return isSelected;
}
public CountryModel(String _name,Drawable _countryFlagIcon){
name = _name;
countryFlagIcon = _countryFlagIcon;
}
public CountryModel(String _name,Drawable _countryFlagIcon,boolean _isSelected){
this(_name,_countryFlagIcon);
isSelected = _isSelected;
}
public void setSelected(boolean _isSelected){
isSelected = _isSelected;
}
#Override
public int hashCode() {
int result = 1;
result = 31 * result + (name == null ? 0 : name.hashCode());
result = 31 * result + Boolean.valueOf(isSelected).hashCode();
return result;
}
#Override
public boolean equals(Object obj) {
if(obj == null || obj.getClass() != getClass()) return false;
if(this == obj) return true;
CountryModel model = (CountryModel)obj;
return name != null && name.equals(model.name) && isSelected == model.isSelected;
}
#Override
public String toString() {
return "[country = " + name + " isSelected = " + isSelected + "]";
}
}
CountryAdapter adapter class for Spinner
public class CountryAdapter extends BaseAdapter {
private static final int VIEW_TYPES = 2;
private static final int TYPE_SELECTED = 0;
private static final int TYPE_UNSELECTED = 1;
private List<CountryModel> countryModelList;
private LayoutInflater layoutInflater;
private CountryChangeListener countryChangeListener;
public CountryAdapter(Context context,CountryChangeListener _countryChangeListener){
countryModelList = new ArrayList<>();
layoutInflater = LayoutInflater.from(context);
countryChangeListener = _countryChangeListener;
}
public void add(List<CountryModel> list){
countryModelList.addAll(list);
}
public synchronized void setCountrySelected(int position) {
updateCountryListDta(position);
if(countryChangeListener != null){
countryChangeListener.onCountryChange(getItem(position));
}
}
public synchronized void setCountrySelected(String selectedCountry) {
for(CountryModel model:countryModelList){
if(model.getName().equals(selectedCountry)){
model.setSelected(true);
}else{
model.setSelected(true);
}
}
}
private void updateCountryListDta(int position) {
for(CountryModel model:countryModelList){
model.setSelected(false);
}
getItem(position).setSelected(true);
}
#Override
public int getCount() {
return countryModelList.size();
}
#Override
public CountryModel getItem(int position) {
return countryModelList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public int getViewTypeCount() {
return VIEW_TYPES;
}
#Override
public int getItemViewType(int position) {
CountryModel model = getItem(position);
return model.isSelected() ? TYPE_SELECTED : TYPE_UNSELECTED;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder viewHolder = null;
if(view == null ){
view = layoutInflater.inflate(R.layout.country_dropdown_item,parent,false);
viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) view.getTag();
viewHolder.checkBox.setOnCheckedChangeListener(null);//remove previous Attached listener
}
CountryModel model = getItem(position);
int type = getItemViewType(position);
viewHolder.checkBox.setChecked(type == TYPE_SELECTED ? true:false);
viewHolder.name.setText(model.getName());
viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
setCountrySelected(position);
}
});
return view;
}
private class ViewHolder{
private TextView name;
private CheckBox checkBox;
ViewHolder(View view){
name = view.findViewById(R.id.countryName);//replace with your resource ids
checkBox = view.findViewById(R.id.countryCheckBox);//replace with your resource ids
}
}
interface CountryChangeListener{
void onCountryChange(CountryModel countryModel);
}
}
You can save the state of your Checkbox in the onsavedinstancestate and retrieve this state in your oncreate method. This is only for shortterm usage, if you want to save the state of your Checkbox for future use of the application you should use a database for the states of each Checkbox or sharedpreferences. For shortterm you can use something like this
override fun onSaveInstanceState(outState: Bundle) {
val checkBox : CheckBox
outState.putBoolean("checkbox_x_checked",checkBox.isChecked)
super.onSaveInstanceState(outState)
}
override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
super.onCreate(savedInstanceState, persistentState)
val checkBox : CheckBox
//assign all Views and Ids
if (savedInstanceState!= null){
checkBox.isChecked = savedInstanceState.getBoolean("checkbox_x_checked",false)
}
}
If you want to save the data for Long term use, you can write the data onchecked into sharedpreferences for example something like this
// get shared preferences
val sharedpref = getSharedPreferences("checked_checkboxes", Context.MODE_PRIVATE)
val sharedpref_editor = sharedpref.edit()
//assign checkboxes
val checkBox_x : CheckBox
//set checkbox old value
checkbox_x.isChecked = sharedpref.getBoolean("checkbox_x_checked",false)
//assign oncheckedchangelistener for the checkboxes
checkBox_x.setOnCheckedChangeListener { buttonView, isChecked ->
sharedpref_editor.putBoolean("checkbox_x_checked",isChecked)
sharedpref_editor.apply()
}

Recyclerview not updating on searchview text change

Friends , I have an edittext which is acting like a searchview.On text change,it is fetching data and storing in filterdNames but it is not updating the recyclerview.Kindly help, i am new to andriod.
Here is my recyclerview adapter code-
public class MyCategoryAdaptercheckbox extends RecyclerView.Adapter<MyCategoryAdaptercheckbox.ViewHolder> {
List<GetMyCategoryAdapter> getMyCategoryAdapter;
Context context;
List<String> category_name;
GetMyCategoryAdapter getMyCategoryAdapter1;
public MyCategoryAdaptercheckbox(List<GetMyCategoryAdapter> getMyCategoryAdapter, Context context, List<String> category_name) {
this.getMyCategoryAdapter = getMyCategoryAdapter;
this.context = context;
this.category_name = category_name;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
if (viewHolder instanceof ViewHolder){
}
getMyCategoryAdapter1 = getMyCategoryAdapter.get(i);
((ViewHolder) viewHolder).tv_categorytitle.setText(getMyCategoryAdapter1.getC_name());
((ViewHolder) viewHolder).tv_categoryid.setText(getMyCategoryAdapter1.getC_id());
((ViewHolder) viewHolder).gt= getMyCategoryAdapter1;
}
public void filterList(ArrayList<String> filterdNames) {
this.category_name = filterdNames;
notifyDataSetChanged();
}
}
Here is my GetMyCategoryAdapter class code -
public class GetMyCategoryAdapter {
String c_name,c_id;
public String getC_name() {
return c_name;
}
public void setC_name(String c_name) {
this.c_name = c_name;
}
public String getC_id() {
return c_id;
}
public void setC_id(String c_id) {
this.c_id = c_id;
}
}
And here is the fragment code -
searchView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
//after the change calling the method and passing the search input
filter(editable.toString());
}
});
private void filter(String text) {
//new array list that will hold the filtered data
ArrayList<String> filterdNames = new ArrayList<>();
//looping through existing elements
for (String s : category_name) {
//if the existing elements contains the search input
if (s.toLowerCase().contains(text.toLowerCase())) {
//adding the element to filtered list
filterdNames.add(s);
}
}
//calling a method of the adapter class and passing the filtered list
((MyCategoryAdaptercheckbox) MyAdapter).filterList(filterdNames);
}
The problem is in filterList method:
you update category_name, but not getMyCategoryAdapter (which is used in onBindViewHolder). Try change getMyCategoryAdapter as well before notifyDataSetChanged

v7 SearchView android

How to filter a RecyclerView with a SearchView(android.support.v7.widget.SearchView) which is not included in toolbar?
I want to filter the results in my recycler adapter using names which i am getting from api in a model.
I have set the recyclerview inside a fragment.
you can simply do it by searchview or edit text
for search view
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
filter(s.toString(),getCustomDeviceCheckItemsList());
return true;
}
});
private void filter(String text,ArrayList<CustomCheckItem> names) {
//new array list that will hold the filtered data
ArrayList<CustomCheckItem> filterdNames = new ArrayList<>();
//looping through existing elements
for (CustomCheckItem s : names) {
//if the existing elements contains the search input
if (s.getTitle().toLowerCase().contains(text.toLowerCase())) {
//adding the element to filtered list
filterdNames.add(s);
}
}
//calling a method of the adapter class and passing the filtered list
childAdapter.filterList(filterdNames);
}
and in adapter you have to write
public void filterList(ArrayList<CustomItem> filterdNames) {
this.list = filterdNames;
notifyDataSetChanged();
}
and if you want to do it by edit text then
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString(),getCustomDeviceCheckItemsList());
}
});

how to get space in edittext filter using custom listview? does it possible using simple adapter?

I have custom listview using simple adapter, Currently I have issue regarding filter that I have custom list data with numbers and characters in listview.
If I enter name then its give one blank space the filter results gets disappear.
I have list data like name then number for example : NAME 123, Whenever I enter name then gives space in that edit text then results are gone and list-view gets disappears.
I have tried this on below link but they used Array adapter, So my question is is it possible only in Array adapter or I can used simple adapter?
Android listview edittext filter space button?
If yes then how can I implement, kindly help. Advance thank you.
try this way
searchView.setOnEditorActionListener(new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
return true;
}
});
addTextChangeListener();
now create method addTextChangeListener
private void addTextChangeListener() {
searchView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence query, int start, int before, int count) {
query = query.toString().trim().toLowerCase();
final ArrayList<CityDataModel> filteredList = new ArrayList<>();
final CharSequence finalQuery = query;
new Thread(new Runnable() {
#Override
public void run() {
// Clear the filter list
filteredList.clear();
// If there is no search value, then add all original list items to filter list
if (TextUtils.isEmpty(finalQuery)) {
filteredList.addAll(cities);
} else {
// Iterate in the original List and add it to filter list...
for (CityDataModel item : cities) {
if (item.getCity_name().toLowerCase().contains(finalQuery.toString().toLowerCase())
) {
// Adding Matched items
filteredList.add(item);
}
}
}
// Set on UI Thread
((Activity) context).runOnUiThread(new Runnable() {
#Override
public void run() {
// Notify the List that the DataSet has changed...
adapter = new SearchCityAdapter(SearchCityClass.this, filteredList);
recyclerSearchCity.setAdapter(adapter);
}
});
}
}).start();
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
You can use any Adapter, you can just implements your adapter with android.widget.Filterable
Example Adapter,
public class AppAdapter extends RecyclerView.Adapter<AppHolder> implements Filterable {
public static final String TAG = AppAdapter.class.getSimpleName();
private ArrayList<App> mApps = new ArrayList<>();
private List<App> mCurrentItmCopy = new ArrayList<>();
private String currentFilter;
private MyArrayFilter mFilter;
#Override
public AppHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View receiverView = LayoutInflater.from(parent.getContext()).
inflate(R.layout.layout_row_apps, parent, false);
return new AppHolder(receiverView);
}
#Override
public void onBindViewHolder(final AppHolder holder, int position) {
final App data = mApps.get(position);
}
#Override
public int getItemCount() {
return mApps.size();
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new MyArrayFilter();
}
return mFilter;
}
private class MyArrayFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
if (mCurrentItmCopy == null || (mCurrentItmCopy.size() == 0)) {
mCurrentItmCopy = new ArrayList<App>(mApps);
}
ArrayList<App> newValues = new ArrayList<App>();
if (prefix != null && !TextUtils.isEmpty(prefix.toString())) {
String prefixString = prefix.toString().toLowerCase();
for (App value : mCurrentItmCopy) {
String label = value.getLabel().toLowerCase();
if ((label.contains(prefixString)) && !newValues.contains(value)) {
newValues.add(value);
}
}
results.values = newValues;
results.count = newValues.size();
} else {
results.values = new ArrayList<App>(mCurrentItmCopy);
results.count = mCurrentItmCopy.size();
mCurrentItmCopy.clear();
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
currentFilter = constraint.toString();
if (results.count > 0) {
mApps.clear();
addAll((ArrayList<App>) results.values);
} else {
mApps.clear();
notifyDataSetChanged();
}
}
}
public void addAll(List<App> items) {
if (items != null) {
mApps.addAll(items);
}
notifyDataSetChanged();
}
}
In the above Adapter instead of App, you can use your object.
You can call from your activity or fragment like this,
mAdapter.getFilter().filter(newText);

Save Checkbox state in RecyclerView

I have a list of options with CheckBoxes in RecyclerView. When I tap on checkbox the state is changed, but after scrolling up and down the state of the checkboxes are losts.
How to save state of checkboxes ? I'm trying to change the state in adapter:
private void setAdapter() {
if (mAdapter == null) {
mAdapter = new FacetChildAdapter(mValues, getActivity(), query.getSpecValueAsString(mParentValue.getSlug())) {
#Override
protected void onCheckBoxRowClicked(CheckboxRow box, Value value, int adapterPosition) {
if (type == FacetChildType.Brands) {
if (box.isChecked()) {
query.removeBrand(value);
} else {
query.addBrand(value);
}
}
else if (type == FacetChildType.Categories) {
if (box.isChecked()) {
query.removeCategory(value);
} else {
query.addCategory(value);
}
}
else if (type == FacetChildType.Deals) {
if (box.isChecked()) {
query.removeDealType(value);
} else {
query.addDealType(value);
}
}
else if (type == FacetChildType.Specifications) {
if (box.isChecked()) {
query.removeSpecification(mParentValue.getSlug(), value);
} else {
query.addSpecification(mParentValue.getSlug(), value);
}
}
box.setChecked(!box.isChecked());
mHeading.setBackText(getResources().getString(R.string.apply));
}
};
mRecyclerView.setAdapter(mAdapter);
} else {
mAdapter.setSource(query.getSpecValueAsString(mParentValue.getSlug()));
mAdapter.refresh(mValues);
}
}
FacetChildAdapter:
public class FacetChildAdapter extends GenericRecycleAdapter<Value, Holders.TextImageHolder> {
private String source;
public FacetChildAdapter(List<Value> list, Context context, String source) {
super(list, context);
this.source = source;
}
public void setSource(String source) {
this.source = source;
}
#Override
protected void onItem(Value s) {
}
public Holders.TextImageHolder getCustomHolder(View v) {
return new Holders.TextImageHolder(v) {
#Override
public void onCheckBoxRowClicked(CheckboxRow v) {
FacetChildAdapter.this.onCheckBoxRowClicked(v, mList.get(getAdapterPosition()), getAdapterPosition());
}
};
}
protected void onCheckBoxRowClicked(CheckboxRow box, Value value, int adapterPosition) {
}
#Override
public int getLayout() {
return R.layout.facet_child_row;
}
#Override
public void onSet(final Value item,final Holders.TextImageHolder holder) {
holder.checkboxRow.setTitle(Html.fromHtml(item.getFullName()));
holder.checkboxRow.setSubText("(" + String.valueOf(item.getCount()) + ")");
holder.checkboxRow.setChecked(ShowProductsWithId.containsValueInValueStringLine(source, item.getSlug()));
holder.checkboxRow.setDisabled(!item.isEnabled());
}
}
It can Maintain in two ways:
1) Use the Hashmap to store the position of check box view.
You can store the position and also store the Unique id of Particular view and then after in Adapter use can easily get the check box position in it.
2) When You can use the Getter setter class then you do create the one integer variable in it and then You can easily set the position in this variable like
When You can check the checkbox then variable value is 1
When You can uncheck the checkbox then variable value is 0
Maintain Your check box Position checked or unchecked in below ways.
class TeamNamesAdapter extends RecyclerView.Adapter<TeamNamesAdapter.ViewHolder>
implements ItemTouchHelperAdapter, View.OnClickListener {
private ArrayList<Person> people;
public TeamNamesAdapter(TinyDB db) {
people = new ArrayList<>();
try {
ArrayList<Object> peopleAsObjects = db.getListObject(PEOPLE, Person.class);
for (Object obj : peopleAsObjects) {
people.add((Person) obj);
}
if (db.getListObject(PEOPLE_ORDER, Person.class) == null) {
db.putListObject(PEOPLE_ORDER, peopleAsObjects);
}
}
catch (NullPointerException e) {
return;
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.team_names_list_item, null);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Person curr = people.get(position);
holder.name.setText(curr.name);
holder.name.setChecked(curr.available);
}
#Override
public int getItemCount() {
return people.size();
}
public void addName(String name) {
if(people.contains(name) || name.isEmpty())
return;
people.add(new Person(name, true));
notifyDataSetChanged();
update(true);
}
#Override
public void onItemDismiss(int position) {
people.remove(position);
notifyItemRemoved(position);
update(true);
}
#Override
public void onItemMove(int fromPosition, int toPosition) {
if (fromPosition < toPosition) {
for (int i = fromPosition; i < toPosition; i++) {
Collections.swap(people, i, i + 1);
}
}
else {
for (int i = fromPosition; i > toPosition; i--) {
Collections.swap(people, i, i - 1);
}
}
notifyItemMoved(fromPosition, toPosition);
update(true);
undoRandomizeButton.setEnabled(false);
}
#Override
public void onClick(View v) {
if (!(v instanceof CheckedTextView))
return;
CheckedTextView ctv = (CheckedTextView) v;
ctv.toggle();
String name = ctv.getText().toString();
for (Person p : people) {
if (p.name.equals(name)) {
p.available = ctv.isChecked();
update(true);
return;
}
}
}
class ViewHolder extends RecyclerView.ViewHolder {
CheckedTextView name;
public ViewHolder(View itemView) {
super(itemView);
name = (CheckedTextView)itemView.findViewById(R.id.name_in_list);
name.setOnClickListener(TeamNamesAdapter.this);
}
}
}
This is a recyclerview adapter for a list that holds a CheckedTextView. I save a class called Person, which contains a string and a bool. You situation is similar, as you can hold only booleans in the ArrayList (instead of Person), and on onBindViewHolder, set checkbox.isChecked to the boolean in that location. And you can set an View.OnClickerListener on the RecyclerView adapter, and set the ViewHolder onClickListener to YourAdapterName.this. And implement the method like I did, just disregard the Person stuff, just update your boolean
You can see that on the adapters onBindViewHolder method,

Categories

Resources