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
}
});
Related
I am using a RecyclerView and an adapter to display the data of an array of Classes objects. I have a MainHolder and two subHolders - ItemHolder and HeaderHolder. ItemHolder has Checkbox. 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 MainHolder:
public abstract class MainHolder extends RecyclerView.ViewHolder {
abstract void setData(MainItem item);
public MainHolder(#NonNull View itemView) {
super(itemView);
}
}
And ItemHolder:
public class ItemHolder extends MainHolder{
private TextView tvTitle, tvComment, tvDate;
private CheckBox cbImportance;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMMM", myDateFormatSymbols);
private static DateFormatSymbols myDateFormatSymbols = new DateFormatSymbols(){
#Override
public String[] getMonths() {
return new String[]{"января", "февраля", "марта", "апреля", "мая", "июня",
"июля", "августа", "сентября", "октября", "ноября", "декабря"};
}
};
#Override
void setData(MainItem item) {
final Event event = item.getEventItem();
tvTitle.setText(event.getName());
tvComment.setText(event.getComment());
tvDate.setText(simpleDateFormat.format(event.getDate()));
cbImportance.setOnCheckedChangeListener(null);
cbImportance.setChecked(event.getImportant());
cbImportance.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
event.IsImportant = b;
}
});
}
public ItemHolder(#NonNull View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.tvTitle);
tvComment = itemView.findViewById(R.id.tvComment);
tvDate = itemView.findViewById(R.id.tvDate);
cbImportance = itemView.findViewById(R.id.cbIconImportant);
}
}
Here's my Adapter
public class MainAdapter extends RecyclerView.Adapter<MainHolder> {
private Context context;
private ArrayList<MainItem> data;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMMM", myDateFormatSymbols);
private OnItemCheckedListener mOnItemChecked;
public interface OnItemCheckedListener{
void onItemChecked(int position, boolean isImportant);
}
public void setOnItemCheckedListener(OnItemCheckedListener listener){
mOnItemChecked = listener;
}
private static DateFormatSymbols myDateFormatSymbols = new DateFormatSymbols(){
#Override
public String[] getMonths() {
return new String[]{"января", "февраля", "марта", "апреля", "мая", "июня",
"июля", "августа", "сентября", "октября", "ноября", "декабря"};
}
};
public MainAdapter(Context context, ArrayList<MainItem> data) {
this.context = context;
this.data = data;
}
#NonNull
#Override
public MainHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
switch (viewType){
case (Constants.ITEM_HEADER_TEXT_VIEWTYPE):
view = LayoutInflater.from(context).inflate(R.layout.group_layout, parent, false);
return new HeaderHolder(view);
case (Constants.ITEM_EVENT_TEXT_VIEWTYPE):
view = LayoutInflater.from(context).inflate(R.layout.list_item_cardview, parent, false);
return new ItemHolder(view);
default: throw new IllegalArgumentException();
}
}
#Override
public void onBindViewHolder(#NonNull final MainHolder holder, final int position) {
holder.setData(data.get(position));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.getItemViewType() == Constants.ITEM_HEADER_TEXT_VIEWTYPE)
Toast.makeText(context, "Нажал на заголовок" + position, Toast.LENGTH_SHORT).show();
else
Toast.makeText(context, "Нажал на айтем" + position, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemViewType(int position) {
return data.get(position).getViewType();
}
Ok, I made the checkbox public in ItemHolder.
And in OnBindHolder I made OnCheckedChanged for Checkbox
#Override
public void onBindViewHolder(#NonNull final MainHolder holder, final int position) {
holder.setData(data.get(position));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.getItemViewType() == Constants.ITEM_HEADER_TEXT_VIEWTYPE)
Toast.makeText(context, "Нажал на заголовок" + position, Toast.LENGTH_SHORT).show();
else
Toast.makeText(context, "Нажал на айтем" + position, Toast.LENGTH_SHORT).show();
}
});
if (holder.getItemViewType() == Constants.ITEM_EVENT_TEXT_VIEWTYPE){
((ItemHolder) holder).cbImportance.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
data.get(position).getEventItem().IsImportant = b;
if (b){
Toast.makeText(context, "IMPORTANT", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, "NON IMPORTANT", Toast.LENGTH_SHORT).show();
}
notifyDataSetChanged();
mOnItemChecked.onItemChecked(position, b);
}
});
}
}
In the fragment I write state of the checkbox.
adapterEvent.setOnItemCheckedListener(new MainAdapter.OnItemCheckedListener() {
#Override
public void onItemChecked(int position, boolean isImportant) {
write(getContext(), events, PROCESSED_EVENTS);
ShowEvents(ShowMode);
}
});
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);
}}
Hello everyone here's my code with recycler view, it works it charges 3 options from my database but my problem is when i try to get all the 3 values in my recycler view
First of all here's my class:
public class OpcionesPonderacionClass {
String Titulo;
public OpcionesPonderacionClass(String titulo) {
Titulo = titulo;
}
public OpcionesPonderacionClass() {
}
public String getTitulo() {
return Titulo;
}
public void setTitulo(String titulo) {
Titulo = titulo;
}
}
Here's my adapter code:
public class OpcionesPonderacionAdapter extends RecyclerView.Adapter<OpcionesPonderacionAdapter.ViewHolderOpcionesPonderacion> {
Context mCtx;
ArrayList<OpcionesPonderacionClass> opcionesPonderacionList;
public OpcionesPonderacionAdapter(Context mCtx, ArrayList<OpcionesPonderacionClass> opcionesList) {
this.mCtx = mCtx;
this.opcionesPonderacionList = opcionesList;
}
#NonNull
#Override
public ViewHolderOpcionesPonderacion onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemopcionponderacion,null);
return new ViewHolderOpcionesPonderacion(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolderOpcionesPonderacion holder, final int position) {
holder.tituloOpcionPonderacion.setText(opcionesPonderacionList.get(position).getTitulo());
holder.npValueOpcionPonderacion.setMinValue(0);
holder.npValueOpcionPonderacion.setMaxValue(10);
}
#Override
public int getItemCount() {
return opcionesPonderacionList.size();
}
public class ViewHolderOpcionesPonderacion extends RecyclerView.ViewHolder {
TextView tituloOpcionPonderacion;
NumberPicker npValueOpcionPonderacion;
public ViewHolderOpcionesPonderacion(#NonNull View itemView) {
super(itemView);
tituloOpcionPonderacion = itemView.findViewById(R.id.tv_TituloOpcionPonderacion);
npValueOpcionPonderacion = itemView.findViewById(R.id.np_ValorNumero);
}
}
}
I can see all the options with their numberpickers from 0 to 10 but for now i'm trying to get a Toast with all the values separated with comma",".
My main problem is how to .getValue() from all the number pickers generated.
You can set up listener to observe value changes within a NumberPicker and collect values in a some Collection.
public static class OpcionesPonderacionAdapter
extends RecyclerView.Adapter<OpcionesPonderacionAdapter.ViewHolderOpcionesPonderacion> {
Context mCtx;
ArrayList<OpcionesPonderacionClass> opcionesPonderacionList;
private final Map<Integer, Integer> pickerValues = new HashMap<>();
private OnNumberPickerValueChangeListener valueChangeListener
= new OnNumberPickerValueChangeListener() {
#Override
public void onValueChange(int position, int value) {
pickerValues.put(position, value);
}
};
public OpcionesPonderacionAdapter(Context mCtx, ArrayList<OpcionesPonderacionClass> opcionesList) {
this.mCtx = mCtx;
this.opcionesPonderacionList = opcionesList;
}
#NonNull
#Override
public ViewHolderOpcionesPonderacion onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemopcionponderacion, null);
return new ViewHolderOpcionesPonderacion(view, valueChangeListener);
}
#Override
public void onBindViewHolder(#NonNull ViewHolderOpcionesPonderacion holder, final int position) {
holder.tituloOpcionPonderacion.setText(opcionesPonderacionList.get(position).getTitulo());
holder.npValueOpcionPonderacion.setMinValue(0);
holder.npValueOpcionPonderacion.setMaxValue(10);
}
#Override
public int getItemCount() {
return opcionesPonderacionList.size();
}
public Map<Integer, Integer> getPickerValues() {
return pickerValues;
}
public class ViewHolderOpcionesPonderacion extends RecyclerView.ViewHolder {
TextView tituloOpcionPonderacion;
NumberPicker npValueOpcionPonderacion;
public ViewHolderOpcionesPonderacion(#NonNull View itemView,
final OnNumberPickerValueChangeListener listener) {
super(itemView);
tituloOpcionPonderacion = itemView.findViewById(R.id.tv_TituloOpcionPonderacion);
npValueOpcionPonderacion = itemView.findViewById(R.id.np_ValorNumero);
npValueOpcionPonderacion.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker,
int oldVal,
int newVal) {
listener.onValueChange(getAdapterPosition(), newVal);
}
});
}
}
interface OnNumberPickerValueChangeListener {
void onValueChange(int position, int value);
}
}
to get values:
#Override
public void onClick(View v) {
final Collection<Integer> values = adapter.getPickerValues().values();
final String result = TextUtils.join(".", values);
Toast.makeText(this, result ,Toast.LENGTH_SHORT).show();
}
I have one recycler View as a parent and a recycler view inside it. I want to update all of my parent recycler view's rows, when I am selecting a row from child recycler view.
In parent recycler view It have two textviews and one recycler view. The increase class and adapter class for parent recycler view is shown below.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rv = (RecyclerView)findViewById(R.id.reviews);
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this);
rv.setLayoutManager(mLinearLayoutManager);
Data();
adapter = new Adapterclass(countryList,MainActivity.this);
rv.setAdapter(adapter);
rv.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(),rv,new ClickListener(){
#Override
public void onClick(View view, int position) {
Log.e("position child",""+position);
adapter = new Adapterclass(position);
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
Adapter class :
public class Adapterclass extends RecyclerView.Adapter<Adapterclass.MyViewHolder> {
private List<ModelMain> flist;
private List<Modelclass>carList;
Context c;
boolean set = false;
int positn;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView text,currency;
RecyclerView recycler;
public MyViewHolder(View view) {
super(view);
text = (TextView)view.findViewById(R.id.gggg);
currency= (TextView)view.findViewById(R.id.hhh);
recycler = (RecyclerView)view.findViewById(R.id.rview2);
}
}
public Adapterclass(List<ModelMain> slist, Context c){
this.flist = slist;
this.c = c;
}
#Override
public Adapterclass.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.cell,parent,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(Adapterclass.MyViewHolder holder, final int position) {
ModelMain fm = flist.get(position);
holder.text.setText(fm.getName());
holder.currency.setText(fm.getCurrency());
carList = new ArrayList<>();
carList = fm.getArrays();
Log.d("list",""+carList.toString());
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(c);
holder.recycler.setLayoutManager(mLinearLayoutManager);
final Adapter_Inside adapter = new Adapter_Inside(carList,c);
holder.recycler.setAdapter(adapter);
holder.recycler.addOnItemTouchListener(new RecyclerTouchListener(c,holder.recycler,new ClickListener(){
#Override
public void onClick(View view, int pos) {
ModelMain mm = flist.get(positn);
carList = new ArrayList<>();
carList = mm.getArrays();
Modelclass mv = carList.get(pos);
Log.e("valll", "" + carList.get(pos).getVal());
Boolean bool = carList.get(pos).getVal();
if(bool){
}else{
for(int i =0; i<carList.size();i++){
Modelclass cls = new Modelclass();
Boolean v = carList.get(i).getVal();
String text = carList.get(i).getText();
if(v){
cls.setVal(false);
cls.setText(text);
carList.set(i,cls);
}
}
mv.setVal(true);
set = true;
}
adapter.notifyDataSetChanged();
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
public Adapterclass(int pos){
this.positn = pos;
}
private void SetAdapr() {
notifyDataSetChanged();
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context applicationContext, final RecyclerView rv, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(applicationContext, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, rv.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
#Override
public int getItemCount() {
return flist.size();
}
Model class for parent recycler view :
public class ModelMain {
String name;
String currency;
List<Modelclass> arrays ;
public ModelMain(String name, String currency, List<Modelclass> arrays) {
this.name = name;
this.currency = currency;
this.arrays = arrays;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public List<Modelclass> getArrays() {
return arrays;
}
public void setArrays(List<Modelclass> arrays) {
this.arrays = arrays;
}
}
And my child recycler view adapter class is :
public class Adapter_Inside extends RecyclerView.Adapter<Adapter_Inside.MyViewHolder> {
private List<Modelclass>carList;
Context c;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView text;
ImageView iv;
public MyViewHolder(View view) {
super(view);
text = (TextView)view.findViewById(R.id.textView);
iv = (ImageView)view.findViewById(R.id.iview);
}
}
public Adapter_Inside(List<Modelclass> slist, Context c){
this.carList = slist;
this.c = c;
}
#Override
public Adapter_Inside.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.secondcell,parent,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(Adapter_Inside.MyViewHolder holder, int position) {
Modelclass fm = carList.get(position);
holder.text.setText(fm.getText());
if(fm.getVal()){
holder.iv.setImageResource(R.drawable.ic_clear_black_18dp);
}
else{
holder.iv.setImageResource(R.drawable.ic_done_black_16dp_2x);
}
}
#Override
public int getItemCount() {
return carList.size();
}
}
And model class for child is :
public class Modelclass {
Boolean val;
String text;
public Boolean getVal() {
return val;
}
public void setVal(Boolean val) {
this.val = val;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
I couldn't retrieve parent recycler view's position when clicking any row in the child view.please help.
You can get reference to your parent RecyclerView by passing it in the Adapter contructor.
public Adapterclass(RecyclerView parent, List<ModelMain> slist, Context c){
this.flist = slist;
this.c = c;
this.recyclerView = parent;
}
Then you can use recycler parent reference and his methods to retrieve all you need
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();
}
});
}