I have recyclerView where i have added a editText. But when I type text to one edittext, text shows another edittext too. Here is the image..
Above image, I type 100 to other item, but it also shows in Settlements
Here is my adapter:
public class AdapterSectionRecycler extends SectionRecyclerViewAdapter<SectionHeader, Child, SectionViewHolder, ChildViewHolder> {
Context context;
private final OnItemClickListener listener;
public interface OnItemClickListener {
void onItemClick(Child child,Boolean isChecked);
}
public AdapterSectionRecycler(Context context, List<SectionHeader> sectionItemList,OnItemClickListener listener) {
super(context, sectionItemList);
this.context = context;
this.listener = listener;
}
#Override
public SectionViewHolder onCreateSectionViewHolder(ViewGroup sectionViewGroup, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.section_item, sectionViewGroup, false);
return new SectionViewHolder(view);
}
#Override
public ChildViewHolder onCreateChildViewHolder(ViewGroup childViewGroup, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_layout, childViewGroup, false);
return new ChildViewHolder(view);
}
#Override
public void onBindSectionViewHolder(SectionViewHolder sectionViewHolder, int i, SectionHeader sectionHeader) {
Log.e("name section--",sectionHeader.getSectionText());
sectionViewHolder.name.setText(sectionHeader.getSectionText());
}
#Override
public void onBindChildViewHolder(ChildViewHolder childViewHolder, int i, int i1, Child child) {
childViewHolder.chk_answer.setText(child.getAnswerName());
childViewHolder.tv_surveyAnswerId.setText(String.valueOf(child.getAnswerId()));
childViewHolder.chk_answer.setChecked(false);
childViewHolder.etPercentage.setImeOptions(EditorInfo.IME_ACTION_DONE);
childViewHolder.etsl.setVisibility(View.GONE);
childViewHolder.chk_answer.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
listener.onItemClick(child,true);
}else{
listener.onItemClick(child,false);
}
}
});
childViewHolder.etPercentage.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) {
}
});
}
}
Here is my Child View holder
public class ChildViewHolder extends RecyclerView.ViewHolder {
CheckBox chk_answer;
EditText etPercentage;
EditText etsl;
TextView tv_surveyAnswerId;
public ChildViewHolder(View itemView) {
super(itemView);
chk_answer = (CheckBox) itemView.findViewById(R.id.chk_answer);
etPercentage = (EditText) itemView.findViewById(R.id.etPercentage);
etsl = (EditText) itemView.findViewById(R.id.etsl);
tv_surveyAnswerId = (TextView) itemView.findViewById(R.id.tv_surveyAnswerId);
}
}
I call from activity:
AdapterSectionRecycler adapterSectionRecycler = new AdapterSectionRecycler(this, sections, new AdapterSectionRecycler.OnItemClickListener() {
#Override
public void onItemClick(Child child, Boolean isChecked) {
}
});
recyclerView_land_conversion.setAdapter(adapterSectionRecycler);
What is the wrong with my code? Please help me..
Related
I have an activity with a list of checkboxes. A checkbox and after clicking it, the next action is called, performed, and completed. Afterward, the action is completed, the app returns to the action with a list of checkboxes and now I want the used checkbox to be checked by default and unable to be clicked again. Please help!
This is what I tried to do but was not successful checkbox becomes unchecked when I return to the action:
P2106.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
Intent move = new Intent(GeneralRoute.this, ScanTest.class);
startActivity(move);
P2106.setChecked(true);
}
}
});
your model class
public class YourModel {
private boolean someBoolean;
private String someString;
private int someInt;
public boolean isSomeBoolean() {
return someBoolean;
}
public void setSomeBoolean(boolean someBoolean) {
this.someBoolean = someBoolean;
}
public String getSomeString() {
return someString;
}
public void setSomeString(String someString) {
this.someString = someString;
}
public int getSomeInt() {
return someInt;
}
public void setSomeInt(int someInt) {
this.someInt = someInt;
}
}
your activity
public class MainActivity extends AppCompatActivity {
private static ArrayList<YourModel> modelList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Add Your Model Or Data To ArrayList
modelList.add(new YourModel());
modelList.add(new YourModel());
ListView listView = findViewById(R.id.youtListView);
YourAdapter yourAdapter = new YourAdapter(this, R.id.youtLayoutListItem, modelList);
listView.setAdapter(yourAdapter);
}
}
and your adapter
public class YourAdapter extends ArrayAdapter<YourModel> {
private ArrayList<YourModel> modelList;
public YourAdapter(#NonNull Context context, int resource, #NonNull List<YourModel> objects) {
super(context, resource, objects);
this.modelList = (ArrayList<YourModel>) objects;
}
#Override
public int getCount() {
return modelList.size();
}
#Nullable
#Override
public YourModel getItem(int position) {
return modelList.get(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if (convertView == null) {
...
}
YourModel model = modelList.get(position);
P2106.setChecked(model.isSomeBoolean());
P2106.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
Intent move = new Intent(GeneralRoute.this, ScanTest.class);
startActivity(move);
P2106.setChecked(true);
model.setSomeBoolean(true);
modelList.set(modelList.indexOf(model), model);
notifyDataSetChanged();
}
}
});
return convertView;
}
}
Don't Forget to replace with your data
i have a search functionality in my app and although is it very limited due to the firebase firestore database queries, i managed to make it work to find string that match the beginning of the user's input.
now everything works fine, even when i write a string for instance "starbucks" and i slowly delete it character by character it resets my recyclerView to full shops available and not only starbucks.
but when i delete quickly (press down on the back button in the keyboard), it stops at that specific shop and doesnt refresh.
what is causing this?
here is my search adapter:
public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.SearchAdapterViewHolder> {
public Context c;
public ArrayList<Shop> arrayList;
public SearchAdapter(Context c,ArrayList<Shop> arrayList){
this.c = c;
this.arrayList = arrayList;
}
#Override
public int getItemCount(){
return arrayList.size();
}
#Override
public long getItemId(int position){
return position;
}
#NonNull
#Override
public SearchAdapterViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.shop_item,parent,false);
return new SearchAdapterViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull SearchAdapterViewHolder holder, int position) {
final Shop shop = arrayList.get(position);
holder.list_name.setText(shop.getName());
String removeBraces = shop.getLocation();
String removeLeftBrace = removeBraces.replace("[","");
String removeRightBrace = removeLeftBrace.replace("]","");
holder.list_location.setText(removeRightBrace);
holder.list_overallRating.setText(""+shop.getRatings());
holder.setHeaderImage(shop.getShopHeaderImg());
holder.list_profileImage(shop.getShopProfileImg());
holder.cardLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, DetailsActivity.class);
intent.putExtra("shopModel", shop);
context.startActivity(intent);
}
});
}
public class SearchAdapterViewHolder extends RecyclerView.ViewHolder {
private RelativeLayout cardLayout;
private TextView list_name;
private TextView list_location;
private TextView list_overallRating;
private ImageView header_img;
private ImageView list_profileImage;
public SearchAdapterViewHolder(#NonNull View itemView) {
super(itemView);
list_name = itemView.findViewById(R.id.list_name);
list_location = itemView.findViewById(R.id.list_location);
list_overallRating = itemView.findViewById(R.id.list_overallRating);
header_img = itemView.findViewById(R.id.header_img);
list_profileImage = itemView.findViewById(R.id.list_profileImage);
cardLayout = itemView.findViewById(R.id.cardLayout);
}
public void setHeaderImage(final String Image) {
final ImageView headerImg = (ImageView)itemView.findViewById(R.id.header_img);
Picasso.get().load(Image).into(headerImg);
}
public void list_profileImage( final String image) {
final ImageView profileImg = (ImageView)itemView.findViewById(R.id.list_profileImage);
Picasso.get().load(image).into(profileImg);
}
}
}
here is my addTextChangeListener:
searchShops.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 s) {
if(!s.toString().isEmpty()){
searchInDB(s.toString().toLowerCase());
}else{
searchInDB("");
}
}
});
and here is my searchInDB function:
private void searchInDB(final String s) {
firebaseFirestore.collection("Shops").orderBy("searchName").startAt(s).endAt(s+"\uf8ff").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()){
QuerySnapshot querySnapshot = task.getResult();
if(!querySnapshot.isEmpty()){
arrayList.clear();
for(QueryDocumentSnapshot DocumentSnapshot : querySnapshot) {
final Shop shop = DocumentSnapshot.toObject(Shop.class);
arrayList.add(shop);
}
SearchAdapter searchAdapter = new SearchAdapter(getApplicationContext(),arrayList);
recyclerView.setAdapter(searchAdapter);
searchAdapter.notifyDataSetChanged();
}else{
arrayList.clear();
}
}else{
}
}
});
Change:
if(!s.toString().isEmpty()){
searchInDB(s.toString().toLowerCase());
}else{
searchInDB("");
}
To
if(!s.toString().isEmpty()){
searchInDB(s.toString().toLowerCase());
}else{
recyclerView.setAdapter(null);
}
I'm trying to crate something that creates a new ListView item on button press, I thing I have somewhere some bug, but as I'm new to this topic I don't know where.
I've tried rewriting the code several times, I've tried to use notifyDataSetChanged(); - it does nothing
tried googling looking on other topics here...
Here is my MainActivity.java:
public Button btn;
private ListView lv;
private CustomeAdapter customeAdapter;
public ArrayList<EditModel> editModelArrayList;
int populateListMaxNum =3;
int listNumber = populateListMaxNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView);
btn = (Button) findViewById(R.id.btn);
editModelArrayList = populateList();
customeAdapter = new CustomeAdapter(this,editModelArrayList);
lv.setAdapter(customeAdapter);
/* TODO activate button */
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addToList();
Toast.makeText(getApplicationContext(), "button", Toast.LENGTH_LONG).show();
}
});
}
private ArrayList<EditModel> populateList(){ //this part works perfectly
ArrayList<EditModel> list = new ArrayList<>();
for(int i = 0; i < populateListMaxNum; i++){
EditModel editModel = new EditModel();
//editModel.setEditTextValue(String.valueOf(i));
list.add(editModel);
}
return list;
}
/*TODO make it work = expand */
private void addToList(){ // this part doesn't work nor it doesn't fail
EditModel editModel = new EditModel();
editModelArrayList.add(editModel);
customeAdapter.notifyDataSetChanged();
}
}
Here is my CustomeAdapter.java class:
public class CustomeAdapter extends BaseAdapter {
private Context context;
public static ArrayList<EditModel> editModelArrayList;
public CustomeAdapter(Context context, ArrayList<EditModel> editModelArrayList) {
this.context = context;
CustomeAdapter.editModelArrayList = editModelArrayList;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
return editModelArrayList.size();
}
#Override
public Object getItem(int position) {
return editModelArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.lv_item, null, true);
holder.editText = convertView.findViewById(R.id.editid);
convertView.setTag(holder);
}else {
// the getTag returns the viewHolder object set as a tag to the view
holder = (ViewHolder)convertView.getTag();
}
holder.editText.setText(editModelArrayList.get(position).getEditTextValue());
holder.editText.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) {
editModelArrayList.get(position).setEditTextValue(holder.editText.getText().toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return convertView;
}
private class ViewHolder {
protected EditText editText;
}
}
I expect to create a new list item (EditText + TextView) but nothing happens (except the Toast message)
(After some tweaks the app crashes due to arrayindexoutofboundsexception length=3 index=3 error, but not in this setting)
here are up to all files nessessary: https://gist.github.com/Atingas/52778a247a78131e5b8cb0239fa30965
Main linear layout in lv_item.xml has match_parent height. Try change it to wrap_content. It seems like one row is just taking whole screen.
I'll use RecyclerView And I've more than 10 items in the list And I Have to change a text color and background layout on a single click of the item and else all the item color not change. Please suggest me the right way to solve this issue. I'll try to change the color in BindViewHolder, ViewHolder and Adapter click item but I'm Successful to change the color but unsuccessful to change the color back.
public class LoadVehicleTypeAdapter extends RecyclerView.Adapter<LoadVehicleTypeAdapter.CarTypesHolder> {
private List<TaxiTypeResponse.Message> CarTypesModelsList;
private Context mContext;
VehicleTypeView vehicleTypeView;
setOnitemclick listener;
private SparseBooleanArray selectedItems = new SparseBooleanArray();
int I=-1;
public class CarTypesHolder extends RecyclerView.ViewHolder {
public CustomTextView mCarType;
public CircleImageView mCarTypeImage;
LinearLayout llRoot;
CardView cardView;
private SparseBooleanArray selectedItems = new SparseBooleanArray();
setOnitemclick listener;
public CarTypesHolder(final View view) {
super(view);
mCarType = (CustomTextView) view.findViewById(R.id.frag_cartypes_inflated_name);
mCarTypeImage = (CircleImageView) view.findViewById(R.id.frag_cartype_inflated_frameImage);
llRoot = (LinearLayout)view.findViewById(R.id.root1);
cardView=(CardView) view.findViewById(R.id.cardf);
}
public void setOnItemClickListner(setOnitemclick listener12) {
listener=listener12;
}
}
public void setOnItemClickListner(setOnitemclick listener12) {
listener=listener12;
}
public LoadVehicleTypeAdapter(Context context, List<TaxiTypeResponse.Message> CarTypesModelsList, VehicleTypeView vehicleTypeView) {
this.CarTypesModelsList = CarTypesModelsList;
mContext = context;
this.vehicleTypeView = vehicleTypeView;
}
#Override
public CarTypesHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.frag_cartype_inflated_view, parent, false);
return new CarTypesHolder(itemView);
}
#SuppressLint("ResourceType")
#Override
public void onBindViewHolder(final CarTypesHolder holder, final int position) {
TaxiTypeResponse.Message carTypesModel = CarTypesModelsList.get(position);
I=CarTypesModelsList.get(position).getID();
holder.mCarType.setText(carTypesModel.getName());
holder.mCarTypeImage.setBackgroundResource(R.drawable.wait);
int color = Color.parseColor(PreferenceHandler.readString(mContext,PreferenceHandler.SECONDRY_COLOR,"#006fb6"));
holder.llRoot.setSelected(selectedItems.get(position, false));
holder.mCarType.setTextColor(color);
holder.setOnItemClickListner(listener);
holder. llRoot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
I=position;
if (I==position)
{
holder.llRoot.setBackgroundColor(Color.parseColor("#999999"));
holder.mCarType.setTextColor(Color.parseColor("#ffffff"));
}
else
{
holder.llRoot.setBackgroundColor(Color.parseColor("#f3f3f3"));
holder.mCarType.setTextColor(Color.parseColor("#00000"));
}
}
});
Picasso.with(mContext).load(carTypesModel.getImagePath()).into(holder.mCarTypeImage);
}
#Override
public long getItemId(int position) {
return CarTypesModelsList.get(position).getID();
}
#Override
public int getItemCount() {
return CarTypesModelsList.size();
}
public void setSelection(LinearLayout imageView,CustomTextView textView,boolean value,int position){
if(value){
imageView.setBackgroundColor(Color.parseColor("#999999"));
textView.setTextColor(Color.parseColor("#FFFFFF"));
}else{
System.out.println("11111111111111111000000111111111111");
imageView.setBackgroundColor(Color.parseColor("#f3f3f3"));
textView.setTextColor(Color.parseColor("#2196F3"));
}
}
public interface setOnitemclick{
void ImageClick(int position, String Name,String Description,int id);
void ImageClickfade(int position, String Name,String Description,int id);
}
#Override
public int getItemViewType(int position) {
return position;
}
}
You can try this,
You'll use to update gradle
maven { url "https://maven.google.com" }
and update the code
public class LoadVehicleTypeAdapter extends RecyclerView.Adapter<LoadVehicleTypeAdapter.CarTypesHolder> {
private List<TaxiTypeResponse.Message> CarTypesModelsList;
private Context mContext;
VehicleTypeView vehicleTypeView;
int I=-1;
public class CarTypesHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public CustomTextView mCarType;
public CircleImageView mCarTypeImage;
LinearLayout llRoot;
CardView cardView;
setOnitemclick listener;
public void setOnItemClickListner(setOnitemclick listener)
{
this.listener=listener;
}
public CarTypesHolder(View view) {
super(view);
mCarType = (CustomTextView) view.findViewById(R.id.frag_cartypes_inflated_name);
mCarTypeImage = (CircleImageView) view.findViewById(R.id.frag_cartype_inflated_frameImage);
llRoot = (LinearLayout)view.findViewById(R.id.root1);
cardView=(CardView) view.findViewById(R.id.cardf);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
listener.ImageClick(v,getAdapterPosition());
}
}
public LoadVehicleTypeAdapter(Context context, List<TaxiTypeResponse.Message> CarTypesModelsList, VehicleTypeView vehicleTypeView) {
this.CarTypesModelsList = CarTypesModelsList;
mContext = context;
this.vehicleTypeView = vehicleTypeView;
}
#Override
public CarTypesHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.frag_cartype_inflated_view, parent, false);
return new CarTypesHolder(itemView);
}
#SuppressLint("ResourceType")
#Override
public void onBindViewHolder( final CarTypesHolder holder, int position) {
TaxiTypeResponse.Message carTypesModel = CarTypesModelsList.get(position);
holder.mCarType.setText(carTypesModel.getName());
holder.mCarTypeImage.setBackgroundResource(R.drawable.wait);
int color = Color.parseColor(PreferenceHandler.readString(mContext,PreferenceHandler.SECONDRY_COLOR,"#006fb6"));
holder.mCarType.setTextColor(color);
holder.setOnItemClickListner(new setOnitemclick() {
#Override
public void ImageClick(View v,int position1) {
I=position1;
notifyDataSetChanged();
}
});
if (I==position)
{
System.out.println("11100011111....");
holder.llRoot.setBackgroundColor(Color.parseColor("#999999"));
holder.mCarType.setTextColor(Color.parseColor("#ffffff"));
}
else
{
System.out.println("11100011111----");
holder.llRoot.setBackgroundColor(Color.parseColor("#f3f3f3"));
holder.mCarType.setTextColor(Color.parseColor("#2196F3"));
}
Picasso.with(mContext).load(carTypesModel.getImagePath()).into(holder.mCarTypeImage);
}
#Override
public long getItemId(int position) {
return CarTypesModelsList.get(position).getID();
}
#Override
public int getItemCount() {
return CarTypesModelsList.size();
}
public void setSelection(LinearLayout imageView,CustomTextView textView,boolean value,int position){
if(value){
imageView.setBackgroundColor(Color.parseColor("#999999"));
textView.setTextColor(Color.parseColor("#FFFFFF"));
}else{
System.out.println("11111111111111111000000111111111111");
imageView.setBackgroundColor(Color.parseColor("#f3f3f3"));
textView.setTextColor(Color.parseColor("#2196F3"));
}
}
public interface setOnitemclick{
void ImageClick(View view,int position);
}
#Override
public int getItemViewType(int position) {
return position;
}
}
Replace your click like below
public void onBindViewHolder(final CarTypesHolder holder, final int position) {
TaxiTypeResponse.Message carTypesModel = CarTypesModelsList.get(position);
I=CarTypesModelsList.get(position).getID();
holder.mCarType.setText(carTypesModel.getName());
holder.mCarTypeImage.setBackgroundResource(R.drawable.wait);
int color = Color.parseColor(PreferenceHandler.readString(mContext,PreferenceHandler.SECONDRY_COLOR,"#006fb6"));
holder.llRoot.setSelected(selectedItems.get(position, false));
holder.mCarType.setTextColor(color);
holder.setOnItemClickListner(listener);
holder. llRoot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
I=position;
holder.llRoot.setBackgroundColor(Color.parseColor("#999999"));
holder.mCarType.setTextColor(Color.parseColor("#ffffff"));
notifyDataSetChanged()
}
});
if (I==position)
{
holder.llRoot.setBackgroundColor(Color.parseColor("#999999"));
holder.mCarType.setTextColor(Color.parseColor("#ffffff"));
}
else
{
holder.llRoot.setBackgroundColor(Color.parseColor("#f3f3f3"));
holder.mCarType.setTextColor(Color.parseColor("#00000"));
}
Picasso.with(mContext).load(carTypesModel.getImagePath()).into(holder.mCarTypeImage);
}
I have build a list of data with a recyclerview. Everything works as expected. But I want to acces some data in my adapter when I click on a cell. The click works. But I don't know how to acces my events list.
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ViewHolder> {
private final LayoutInflater layoutInflater;
private final Context context;
private ArrayList<Event> events;
public ExampleAdapter(Context context, ArrayList<Event> events) {
this.context = context;
layoutInflater = LayoutInflater.from(context);
this.events = events;
}
#Override
public ExampleAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(layoutInflater.inflate(R.layout.activity_row, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
//holder.textView.setText(titles[position]);
holder.title.setText(events.get(position).getTitle());
holder.time.setText(events.get(position).getTime());
holder.places.setText(events.get(position).getPlacesLeft());
}
public void add(ArrayList<Event> events){
this.events = events;
this.notifyDataSetChanged();
}
#Override
public int getItemCount() {
return events == null ? 0 : events.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView title;
TextView time;
TextView places;
ViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.activity_title);
time = (TextView) view.findViewById(R.id.activity_time);
places = (TextView) view.findViewById(R.id.activity_places);
//textView = (TextView) view.findViewById(R.id.text_view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("ViewHolder", "onClick--> position = " + getPosition());
}
});
}
}
}
I have declared the onclick listener in the ViewHolder class. The click listener works as expected. But I want to acces the data in my events array. The only problem is that I can't acces it.
your onclick should be inside your onBindViewHolder
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
//holder.textView.setText(titles[position]);
holder.title.setText(events.getTitle());
holder.time.setText(events.getTime());
holder.places.setText(events.getPlacesLeft());
holder.yourview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
//access from here
Toast.makeText(yourActivity.this,holder.yourview.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
}
If you just want to handle the click on the item you can do like this :
In your adapter write a function to get an event at a position :
public Event getEventAtPosition(int position) {
if (events != null && events.size() > position)
return events.get(position);
else return null;
}
Then implement a RecyclerTouchListener :
public interface ClickListener{
void onClick(View view,int position);
void onLongClick(View view,int position);
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private ClickListener clicklistener;
private GestureDetector gestureDetector;
public RecyclerTouchListener(Context context, final RecyclerView recycleView, final ClickListener clicklistener){
this.clicklistener=clicklistener;
gestureDetector=new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child=recycleView.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null){
clicklistener.onLongClick(child,recycleView.getChildAdapterPosition(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.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
Finally, you can use it this way :
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this,
recyclerView, new ClickListener() {
#Override
public void onClick(View view, final int position) {
Event event= ((EventListAdapter)recyclerView.getAdapter()).getEventAtPosition(position);
}
#Override
public void onLongClick(View view, int position) {
}
}));
This way, you have only 1 ClickListener for all your recycler view, this is more optimal than declaring a listener for each item.
For more informations about RecyclerView and onClick, check this topic : RecyclerView onClick