Issue
I'm trying to make an on-click method for recycle List items. I have found that you can make it inside the Adapter you have made for the list inside the OnBindViewHolder, and it works, however, I do not have access to the EditTexts that are in the Activity where the Adapter is used , I was wondering if there is a way to import them to be used in the Adapter ? Thank you in advance.
Solution
You can do it, You have to use Interface for this purpose.
Interface will pass your data from Adapter to your Activity having that EditText. Then you update your EditText accordingly.
Create an Interface
public interface DataTransferInterface {
public void onItemClicked(String data);
}
Create Object of Interface in Adapter
DataTransferInterface dtInterface;
Initialize it in Constructor of your adapter
public MyAdapter(DataTransferInterface dtInterface) {
this.dtInterface = dtInterface;
}
When Any item is Clicked in Adapter pass data to Activity
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
dtInterface.onItemClicked("Data to be passed here");
}
});
Now in your Activity
implement that interface like:
public class MainActivity extends Activity implements DataTransferInterface {
When you implement Interface in Activity, It will show error to implement its required methods. SO,
@Override
public void onItemClicked(String Data) {
// TODO Update your EditText Here
}
Initialize your adapter like
myAdapter = new MyAdapter(this);
If you find any difficulties, You can read more here
Answered By - Ali Ahmed
Answer Checked By - Katrina (JavaFixing Volunteer)