I have customrecycleAdapter and when I click on element i would change color of row, but if I scroll view background change position or appear on other element. I have read about Receycle of view, but so, What is workoround for this problem?
my adapter is:
public class CustomRecycleAdapter extends RecyclerView.Adapter<CustomRecycleAdapter.ViewHolder> {
private JSONArray dataSource;
private AdapterCallback mAdapterCallback;
public static SparseBooleanArray selectedItems;
public CustomRecycleAdapter(JSONArray dataArgs, Context context){
dataSource = dataArgs;
this.mAdapterCallback = ((AdapterCallback) context);
}
public static interface AdapterCallback {
void onMethodCallback(View caller, JSONObject obj, JSONArray data, int position);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_view_activities, parent, false);
ViewHolder viewHolder = new ViewHolder(view, new CustomRecycleAdapter.ViewHolder.IMyViewHolderClicks() {
public void onClick(View caller, int position) {
try {
JSONObject itemClicked = dataSource.getJSONObject(position);
mAdapterCallback.onMethodCallback(caller, itemClicked, dataSource, position);
// Log.e("clicked", itemClicked.toString());
} catch (JSONException e) {
e.printStackTrace();
}
};
});
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
try {
JSONObject object = dataSource.getJSONObject(position);
holder.textView.setText(object.getString("description"));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return dataSource.length();
}
public JSONObject getItem(int position) throws JSONException {
return dataSource.getJSONObject(position);
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public IMyViewHolderClicks mListener;
public TextView textView;
public TextView hours;
public ViewHolder(View itemView, IMyViewHolderClicks listener) {
super(itemView);
mListener = listener;
textView = (TextView) itemView.findViewById(R.id.activity);
hours = (TextView) itemView.findViewById(R.id.hours);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int position = getAdapterPosition();
Log.e("RecycleAdapterPosition", String.valueOf(getAdapterPosition()));
// mListener.onClick(v, position);
v.setBackgroundColor(Color.GREEN);
v.setSelected(true);
}
public interface IMyViewHolderClicks {
public void onClick(View caller, int position);
}
}
}
So I click on element, and corretly setBackground, but if I scroll, I see another element with background setted and if I scroll up my element, that i selected, haven't background.