My RecyclerView is a list with checkboxes and at the bottom of the page is a submit button. When I click on the button, the checkboxes should be disabled but the state of those boxes that are already checked should retain. And also, how to access the checkbox since it's in the RecyclerView.ViewHolder? Help please.
It's much better to have this as an attribute to the item that you're modeling.
So if the model item will have an "enabled" state that you can change.
public class Model {
private boolean isEnabled;
private boolean isChecked;
public void setEnabled(boolean enabled) {
isEnabled = enabled;
}
public void setChecked(boolean checked) {
isChecked = checked;
}
public boolean isEnabled() {
return isEnabled;
}
public boolean isChecked() {
return isChecked;
}
}
Then your ViewHolder will check this attribute every time you bind to it. Additionally, the ViewHolder itself will listen for changes to the checkbox on the View that it handles.
public class ModelViewHolder extends RecyclerView.ViewHolder implements CompoundButton.OnCheckChangeListener {
private CheckBox checkBox;
private Model boundItem;
public ModelViewHolder(View itemView) {
checkBox = (CheckBox) itemView.findItemById(R.id.checkBoxId);
checkBox.setOnCheckChangeListener(this);
}
public void bind(Model model) {
boundItem = model;
getItemView().setEnabled(model.isEnabled());
checkBox.setChecked(model.isChecked());
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
boundItem.setChecked(isChecked);
}
}
Now, what this allows is the state of the item will be consistent while the user scrolls (since Views in RecyclerItem are re-used). It also allows you to use notifyItemChanged(int position) more easily on the item whenever you enable/disable the Model item.
You will need to get your item in the list you passed to the adapter. If it is a custom adapter you can make a method to return your list, and code will be:
mAdapter.getList().get(4).setEnabled(false); //or equivalent
mAdapter.notifyDataSetChanged(); //or mRecycler.getAdapter().notifyDataSetChanged()
Change the Recyclerview background colour is Gray. In Recyclerview disable only work when some action is performed. if try to disable no action is performed, You have NULL Pointer exception.
You can try that:
RecyclerView rv=new RecyclerView(context);
rv.getChildAt(5).setEnabled(false); // disables the 6th element
Related
I'm trying to set up a checkbox in my recycler view, but I'm facing the common problem of random checks without my control. I check one item and some more random items are being checked at the same time.
I realise this is a common question here, but the solutions I found here don't seem to work. Among many others I was trying to follow different instructions in this thread:
Android RecyclerView checkbox checks itself
but what seems to be the problem is that functions isSelected and setSelected can't be resolved.
My best guess is that the reason for this complication might be that my onCheckedChange action is actually interfaced from the main activity, as you can see at the bottom of the code below. Is that what complicates the code (can't avoid it)?
public LocationRecyclerViewAdapter(List<IndividualLocation> styles,
Context context, ClickListener cardClickListener, OnCheckedChangeListener checkedChangeListener, int selectedTheme) {
this.context = context;
this.listOfLocations = styles;
this.selectedTheme = selectedTheme;
this.clickListener = cardClickListener;
this.onCheckedChangeListener = checkedChangeListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int singleRvCardToUse = R.layout.single_location_map_view_rv_card;
View itemView = LayoutInflater.from(parent.getContext()).inflate(singleRvCardToUse, parent, false);
return new ViewHolder(itemView);
}
public interface ClickListener {
void onItemClick(int position);
}
public interface OnCheckedChangeListener {
void onCheckboxClick(int position);
}
#Override
public int getItemCount() {
return listOfLocations.size();
}
#Override
public void onBindViewHolder(final ViewHolder card, int position) {
final IndividualLocation locationCard = listOfLocations.get(position);
card.nameTextView.setText(locationCard.getName());
card.addressTextView.setText(locationCard.getAddress());
card.hoursTextView.setText(locationCard.getHours());
card.priceTextView.setText(locationCard.getPrice());
card.categoryTextView.setText(locationCard.getCategory());
card.cuisineTextView.setText(locationCard.getCuisine());
card.happyHourTextView.setText(locationCard.getHappyHour());
card.lunchDealTextView.setText(locationCard.getLunchDeal());
card.websiteTextView.setText("WEBSITE");
card.newPlaceTextView.setText(locationCard.getNewPlace());
card.websiteTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String url = locationCard.getWebsite();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
context.startActivity(intent);
}
});
static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView nameTextView;
TextView addressTextView;
TextView priceTextView;
TextView hoursTextView;
TextView categoryTextView;
TextView cuisineTextView;
TextView happyHourTextView;
TextView lunchDealTextView;
TextView newPlaceTextView;
ConstraintLayout constraintUpperColorSection;
CardView cardView;
ImageView backgroundCircleImageView;
ImageView emojiImageView;
Button websiteTextView;
CheckBox checkBox;
ViewHolder(View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.location_name_tv);
addressTextView = itemView.findViewById(R.id.location_description_tv);
priceTextView = itemView.findViewById(R.id.location_price_tv);
hoursTextView = itemView.findViewById(R.id.location_hours_tv);
backgroundCircleImageView = itemView.findViewById(R.id.background_circle);
emojiImageView = itemView.findViewById(R.id.emoji);
constraintUpperColorSection = itemView.findViewById(R.id.constraint_upper_color);
categoryTextView = itemView.findViewById(R.id.location_type_tv);
cuisineTextView = itemView.findViewById(R.id.location_cuisine_tv);
happyHourTextView = itemView.findViewById(R.id.happyhour_tv);
lunchDealTextView = itemView.findViewById(R.id.lunchdeal_tv);
cardView = itemView.findViewById(R.id.map_view_location_card);
websiteTextView = itemView.findViewById(R.id.website);
newPlaceTextView = itemView.findViewById(R.id.new_place);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickListener.onItemClick(getLayoutPosition());
}
});
checkBox = itemView.findViewById(R.id.checkBox);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
onCheckedChangeListener.onCheckboxClick(getLayoutPosition());
}
}});
}
#Override
public void onClick(View view) {
}
}
}
I'm sure there is some simple solution to this, but I've been cracking my head over this for way too long now. Thanks!
First of all, you have to check the checkbox programatically, for every item. Your model should hold the data, a simple boolean could do it.
The second is the trickiest one
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView.isPressed()){
if (isChecked ) {
onCheckedChangeListener.onCheckboxClick(holder.getAdapterPosition()());
}}
}});
You have to check if the checkbox is actually checked, in order to avoid confusions,
Inside your onBindViewHolder you have to set your checkbox either checked or unchecked. if true, your checkbox will be selected, else unselected,
because recycler view will be recycled every time you scroll, so you need to make sure you need to tell adapter that checkbox need to be checked or unchecked at that particular position.
why are you using getLayoutPosition() for getting checkbox position
use like this holder.getAdapterPosition()
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
onCheckedChangeListener.onCheckboxClick(holder.getAdapterPosition()());
}
}});
and move this listener to your onBindViewHolder()
Your data model should have a boolean variable isChecked. You can also give it an default value false. Now, in your adapter function onBindViewHolder, you should set value of your checkbox ex.
card.checkBox.setChecked(locationCard.getIsChecked())
Also, in your onCheckedChanged you should update your data
locationCard.setIsChecked(isChecked)
Now each time your RecyclerView Adapter reuses and list item, it will set the value of its checkbox correctly. Hope this helps.
I have a RecyclerView list with CheckBox in the CardView, using a simple onClickListener. But when index 0 is clicked index 10 is also shown as clicked. The same if index 1 is clicked so is 11, index 2 so is 12, and so on. How do I solve this problem?
Three steps to solve it, and can be used everywhere you have a checkbox widget and it will be resued.
Firstly, Each adapter has a corresponding 'bean' binds to it. for example, List, The T is the bean.
Secondly, add a boolean field 'ischecked' into 'bean' class.
Finally, use this field to reset the status of checkbox when recycleview reuses checkbox, and update it when status of checkbox being changed.
RecyclerView will reuse the layouts from previous rows when scrolling, so if you check item 1, and scroll, item 11 will still be checked unless told to not be.
Within your onBindViewHolder, you want to set the layout to the current state of the object you're displaying.
For example, say we have a list of Dogs, and we can mark if we've pet the Dog.
class Dog {
public boolean hasPet = false;
public String name;
}
Now, if you're displaying each Dog, you can do.
void onBindViewHolder(MyViewHolder holde, int position) {
Dog dog = list[position];
holder.name = dog.name;
// Remove any onCheckChangeListener or else we'll change the previously rendered dog.
holder.check.setOnCheckedChangeListener(null);
// Set the checkbox to the current state of the dog.
holder.check.setChecked(dog.hasPet);
// Add a new onCheckChangeListener with the current dog.
holder.check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Logger.d("Clicked.");
dog.hasPet = isChecked;
}
});
}
This is because of the behavior of your RecyclerView. RecyclerView tries to recycle the views generated already with minimal changes in data. So in order to populate your data precisely in your list items, you need to tell exactly what it needs to show.
In your case, you need to keep the track of your checkbox click somewhere (maybe in a different array) so that you can populate the views accordingly. Let us consider the following code.
// Let us create an integer array having the same size of your list that is being passed to your RecyclerView
// Initially, all elements in the array is zero.
private int[] array = new int[yourList.size()];
Now in your onBindViewHolder, I think you have implemented the onClickListener for your CheckBox. Hence when you are clicking the CheckBox, set the corresponding element in your array to 1.
public void onClick(int position) {
// Checbox click action here
if (array[position] == 0)
array[position] = 1; // Use the position of your adapter to set the value.
else array[position] = 0; // Toggle the values on check/uncheck
}
Now in the onBindViewHolder while populating the CheckBox, check the value of its position in the array and set the checked status accordingly.
if(array[position] == 1) checkBox.setChecked(true);
else checkBox.setChecked(false);
Hope that helps!
The problem because you didn't keep the click state for each item. You can modify your pojo and adding a check state property or you can simply using SparseBooleanArray to hold the check state for all items.
Here the sample for using SparseBooleanArray.
Assuming we're using a simple pojo of User:
public class User {
private String id;
private String name;
// constructor, setter, getter
}
First, create a SparseBooleanArray to hold the selected flags like this:
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
private List<User> mUsers;
private SparseBooleanArray mSelectedFlags;
public UserAdapter(List<User> users) {
mUsers = users;
mSelectedFlags = new SparseBooleanArray();
}
...
}
Second, save the state whenever you click the CheckBox in your ViewHolder:
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvName;
public TextView tvId;
public CheckBox cbxSelect;
public ViewHolder(View itemView) {
super(itemView);
...
// bind view here
cbxSelect.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// set the state for specific item by its position.
mSelectedFlags.put(getAdapterPosition()), isChecked);
}
});
}
Last, set the state in onBindViewHolder:
#Override
public void onBindViewHolder(ContactsAdapter.ViewHolder viewHolder, int position) {
int itemPosition = viewHolder.getAdapterPosition();
User user = mUsers.get(itemPosition);
viewHolder.tvId.setText(user.getId());
viewHolder.tvName.setText(user.getName());
// set the check state for each item
// SparseBooleanArray will return false as default value
viewHolder.cbxSelect.setChecked(mFlagSelected.get(itemPosition));
}
The full adapter will be something like this:
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
private List<User> mUsers;
private SparseBooleanArray mSelectedFlags;
public UserAdapter(List<User> users) {
mUsers = users;
mSelectedFlags = new SparseBooleanArray();
}
#Override
public UserAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
...
// inflate and return view holder.
return viewHolder;
}
#Override
public void onBindViewHolder(ContactsAdapter.ViewHolder viewHolder, int position) {
int itemPosition = viewHolder.getAdapterPosition();
User user = mUsers.get(itemPosition);
viewHolder.tvId.setText(user.getId());
viewHolder.tvName.setText(user.getName());
// set the check state for each item
// SparseBooleanArray will return false as default value
viewHolder.cbxSelect.setChecked(mFlagSelected.get(itemPosition));
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvName;
public TextView tvId;
public CheckBox cbxSelect;
public ViewHolder(View itemView) {
super(itemView);
...
// bind view here
cbxSelect.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// set the state for specific item by its position.
mSelectedFlags.put(getAdapterPosition()), isChecked);
}
});
}
}
I have a RecyclerView with a large list of items. This RecyclerView has OnScrollListener for endless scrolling.
When an item is selected I highlight it with a specific colour and
when unselected the colour changes to normal/white.
The issue that I am facing is after selecting a few visible items in my view when I scroll up or down to select a few more items the colour of already selected items changes to white.
I tried adding a boolean variable (isSelected) in the model class and highlight the selected item but still I am facing the same issue as earlier. Currently the recyclerView allows to select just one item from the view and after some research I figured some of the concepts were taken from this article to implement single item selection. I wonder how do I modify/tweak this code to be able to select multiple items.
I am not presenting the code as it is quite huge and is confidential but if there is any general fix for this scenario then what would it be?
Background: the application is a chat app and I am showing the sent and received texts. The user should be able to select a few specific texts and should be able to share it with someone else.
Edit: I am putting the code in my onBindViewHolder:
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final PostDataColumns mPostDataColumns = data.get(position);
holder.textCardView.setBackgroundColor(mPostDataColumns.isSelected() ? getResources().getColor(R.color.long_press):
getResources().getColor(android.R.color.white));
holder.textCardView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
mPostDataColumns.setSelected(!mPostDataColumns.isSelected());
if(mPostDataColumns.isSelected()) {
holder.textCardView.setBackgroundResource(R.color.long_press);
multipleSelectedPositions.add(holder.getLayoutPosition());
} else if(!mPostDataColumns.isSelected()) {
holder.textCardView.setBackgroundResource(android.R.color.white);
multipleSelectedPositions.remove(holder.getAdapterPosition());
}
//Adapter.this.onLongClick(holder, position);
return true;
}
});
holder.textCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.textCardView.setBackgroundResource(android.R.color.white);
/* clearLongSelection(holder, position, alignParentRight,
data.get(position).getReceiverUserId().length() > 5); */
}
});
}
The code which I have commented in onCLick and onLongClick were used when the requirement was to select a single item.
these are the methods which were called in onClick and onLOngClick:
public boolean clearLongSelection(ViewHolder holder, int position) {
if (selectedPosition >= 0) {
if (selectedPosition == position) {
holder.parentLayout.setBackgroundResource(android.R.color.transparent);
if (alignParentRight) {
holder.mediaCardView.setBackgroundResource(android.R.color.white);
holder.assessmentCardView.setBackgroundResource(android.R.color.white);
holder.surveyCardView.setBackgroundResource(android.R.color.white);
holder.documentCardView.setBackgroundResource(android.R.color.white);
holder.textCardView.setBackgroundResource(android.R.color.white);
} else {
holder.mediaCardView.setBackgroundResource(R.color.long_press);
holder.assessmentCardView.setBackgroundResource(R.color.long_press);
holder.surveyCardView.setBackgroundResource(R.color.long_press);
holder.documentCardView.setBackgroundResource(R.color.long_press);
holder.textCardView.setBackgroundResource(R.color.long_press);
}
selectedPosition = -1;
invalidateOptionsMenu();
getSupportActionBar().setTitle(intentData.getName());
}
return true;
}
return false;
}
public void onLongClick(ViewHolder holder, int position) {
if (selectedPosition < 0) {
holder.parentLayout.setBackgroundResource(R.color.long_press);
holder.mediaCardView.setBackgroundResource(R.color.long_press);
holder.assessmentCardView.setBackgroundResource(R.color.long_press);
holder.surveyCardView.setBackgroundResource(R.color.long_press);
holder.documentCardView.setBackgroundResource(R.color.long_press);
holder.textCardView.setBackgroundResource(R.color.long_press);
selectedPosition = position;
invalidateOptionsMenu();
getSupportActionBar().setTitle("1 Selected");
} else {
}
}
The variable selectedPosition in onClick and clearLongSelection is initialised in the class as instance variable- selectedPosition = -1.
Use SparseBooleanArray to keep track of selected items in recycler view adapter
Initialize the SparseBooleanArray as private memeber variable
private SparseBooleanArray mClickedItems=new SparseBooleanArray();
Then inside your click function while clicking any item,store the clicked item position as true.
mClickedItems.put(getAdapterPosition(),true);
notifyDataSetChanged();
Then in the onBindViewHolder check if the position is already selected or not like this
if(mClickedItems.get(position)==true){
//Show selected color
}else {
//show unselected color
}
I have a RecyclerView which holds 10 views each having a CheckBox. Now, in my main activity when a menu button named "POST" is pressed I want to know whether all the CheckBox in each of the views of the RecyclerView is checked or not.
How can I implement this?
I advise you to pass additional variable isChecked inside every model of a list of models passed to RecyclerView.
Like that:
public class Model {
private boolean isChecked;
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean checked) {
isChecked = checked;
}
}
Then inside your RecyclerView ViewHolder, create a constructor:
public ListViewHolder(View view) {
super(view);
switchCompat = (SwitchCompat) view.findViewById(R.id.add_switch);
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
getItemAt(getLayoutPosition()).setChecked(isChecked);
}
});
}
Then to get all button states just iterate through the list of models in Your activity:
public boolean areAllChecked() {
for (int i = 0; i < adapter.getItemCount(); i++) {
Model model = adapter.getItemAt(i);
if (!model .isChecked()) {
return false;
}
}
return true;
}
Add a boolean isChecked in your model class (Item which you are adding to RecyclerView Adapter)
In your adapter onBindViewHolder implement onCheckedChangeListener for your checkbox and set isChecked appropriately.
implement a isChecked(int position) method in your adapter. It should return checked value of the items specified by position
in your fragment/activity iterate through adapter items and find out if all items are checked or not.
Track the state of each checkbox in the adapter.
To do so let it have an map that stores a boolean value bound to a unique key for each checkbox. And also let it implement the OnCheckedChangeListener.
MyAdapter extends RecyclerView.Adapter implements OnCheckedChangeListener {
private Map<Object, Boolean> checkboxStates = new HasMap<>();
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkboxStates.put(buttonView.getTag(), isChecked);
}
public Map<Object, Boolean> getCheckboxStates() {
//We don't want the caller to modify adapter state.
return Collections.unmodifiableMap(this.checkboxStates);
}
//other code
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
//your code
CheckBox cb;
//assuming that we have the reference to the cb view
//also assuming that cb has a unique identifiable tag assigned from the model
cb.setOnCheckedChangeListener(this);
if (this.checkboxStates.containsKey(cb.getTag()) {
cb.setChecked(this.checkboxStates.get(cb.getTag());
} else {
this.checkboxStates.put(cb.getTag(), cb.isChecked());
}
}
}
With this you can call the getCheckboxStates to get the states of each checkbox that was visible.
The key point here is that you need something unique identifiable for each item in the dataset that can be used as a tag for each checkbox that represents that item.
I've got "for each" loop that creates textView for every obiect from the list and add them to the linear layout. It works great. Then I want to hide all of the textViews when user clicks on toggle button but here I've got problem - only the last textView from the list is being hidden , rest of them is still visible. I tried to solve this problem with many solutions ( for example with getChild()), but nothing works.
final List<FilterItem> filterItemList = filterData.getFilterItemList();
for (FilterItem filterItem : filterItemList) {
final TextView filter = new TextView(MainPanelActivity.this);
filter.setText(filterItem.getFilterItemName());
filter.setTextColor(R.color.black);
linearLayout.addView(filter);
filter.setVisibility(View.GONE);
textLine.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
filter.setVisibility(View.VISIBLE);
} else {
filter.setVisibility(View.GONE);
}
}
});
Note that youre setting a listener for textLine inside the for loop - so for each iteration you set a new listener that changes the visibility of the TextView created in the current iteraton.
Move textLine.setOnCheckedChangeListener() outside of the for loop; and inside onCheckedChanged - loop through all children of linearLayout and set the visibility for each child.
textLine.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
for (View v : linearLayout.getChildren()) {
if (v instanceof TextView) {
if (isChecked) {
v.setVisibility(View.VISIBLE);
} else {
v.setVisibility(View.GONE);
}
}
}
You could keep a list of TextViews when you create them. Then set the click listener outside the for-loop as Dmitri says, which would iterate through the list of TextViews and set the visibility to GONE.
private void setup() {
List<View> textViews = new ArrayList<>();
for (FilterItem filterItem : filterData.getFilterItemList()) {
View view = createTextViewFor(filterItem);
linearLayout.addView(filter);
textViews.add(view);
}
updateVisibility(textViews, View.GONE);
textLine.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int visibility = isChecked ? View.VISIBLE : View.GONE;
updateVisibility(textViews, visibility);
}
}
);
}
private View createTextViewFor(FilterItem filterItem) {
TextView view = new TextView(MainPanelActivity.this);
view.setText(filterItem.getFilterItemName());
view.setTextColor(R.color.black);
view.addFilter(filterItem);
return view;
}
private void updateVisibility(List<View> views, int visibility) {
for (View view : views) {
view.setVisibility(visibility);
}
}
In case you want to display textView dynamically, I think putting textView inside RecyclerView will be a better idea. RecyclerView has its own Adapter which will make it easy to play with data and textViews. Give recyclerView a try. RecycerView for what you are trying to do can be learnt in few hours and sky is the limit for what you can do with recyclerView :)