Search code examples
androidcustom-adapter

how can i use views from my method in custom adapter?


I was try change textview background color in my custom adapter and i created a method because i want to achieve this method from my activity. So i want to use my views in my method in custom adapter like how we re using holder.txt_product.... in onBindViewHolder() method.

@Override
public void onBindViewHolder(final DeMontageListAdapter.MyViewHolder holder, 
final int position) {

    holder.txt_piston_code.setText(list.get(position).getPistonCode());
}

@Override
public int getItemCount() {
    return list.size();
}

public void changeTextViewBackground(){


}

i want to actieve my views like onBindViewHolder() method at my changeTextViewBackground() method.


Solution

  • You need to implement and set a listener interface for your viewholders to be able to communicate with them through your activity:

    Your custom adapter:

         private OnItemClickListener onItemClickListener; //ADD THIS GLOBAL FIELD
    
         //ADD THIS SETTER
         public void setOnItemClickListener(OnItemClickListener onItemClickListener) 
         {
             this.onItemClickListener = onItemClickListener;
         }
    
         @Override
         public void onBindViewHolder(final DeMontageListAdapter.MyViewHolder holder, 
         final int position) {
    
         holder.txt_piston_code.setText(list.get(position).getPistonCode());
    
         // SET YOUR LISTENER TO EACH OF YOUR ITEM VIEWS
         holder.txt_piston_code.setOnClickListener(v ->
                onItemClickListener.onClickItem(position);
         }
    
         // ADD THIS INTERFACE AT THE END
         interface OnItemClickListener {
            void onClickItem(int position);
         }
    

    Your activity should implement DemontageListAdapter.OnItemClickListener and Override its onClickItem method:

        public class MyActivity implements DemontageListAdapter.OnItemClickListener {
    
            DemontageListAdapter adapter;
    
            { ... }
    
            adapter = new DemontageListAdapter (...)
            adapter.setOnItemClickListener(this); // ADD THIS BEFORE YOU SET YOUR ADAPTER TO YOUR ACTIVITY
            recyclerView.setAdapter(adapter);
    
            //OVERRIDE THIS METHOD OF YOUR INTERFACE
            @Override
            public void onClickItem(int position) {
                adapter.changeTextViewBackground(position);
            }
        }