问题
I want to create an interface between an adapter and a view holder (this view holder is an inner class of another adapter) so that I can update the text view (number). How can I do this?
In detail:
I have two recycle views (Main List Recycler View and Sub List Recycler View horizontally placed as shown in the fig) one having a number (as one of its item) and other having checkbox (as its item).
I have two adapters FilterMainListAdapter
and FilterSubListAdapter
with view holders FilterMainListViewHolder
and FilterSubListViewHolder
populating the fields.
When checkboxes are selected in the Sub List Recycler View, I want the corresponding number in the Main List Recycler View to update.
For this, I'm using and Interface.
public interface ChangeFilterMainNumber {
void OnChangeFilterMainNumberListener(int totalCheckedNumber);
}
I've checkbox's onClick method inside the FilterSubListViewHolder
and I'm trying to send the total check boxes checked number as follows.
changeFilterMainNumber.OnChangeFilterMainNumberListener(totalCheckedNumber);
After that, I'm implementing ChangeFilterMainNumber
interface inside the FilterMainListViewHolder
public class FilterMainListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
ChangeFilterMainNumber {...}
But How can I define this interface inside the FilterSubListAdapter
?
changeFilterMainNumber = ???;
[If it is an activity one can define the interface like this changeFilterMainNumber = (ChangeFilterMainNumber) context
inside the default constructor of FilterSubListAdapter
. But what about a view holder that is an inner class of another adapter?]
or is there a better approach in finding a solution to my problem other than this?
Update: You can take a look at the code here https://github.com/gSrikar/FilterScreen
回答1:
If I implement the function as you want, I will implement like this: (This is like an Observer pattern)
class Fragment/Activity implement OnChangeFilterMainNumberListener{
FilterMainListAdapter mainAdapter;
FilterSubListAdapter subAdapter;
void oncreate() {
mainAdapter = new FilterMainListAdapter(this);
}
@Override
void OnChangeFilterMainNumberListener(int totalCheckedNumber) {
.....
// Update data to sub list
}
}
class FilterMainListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
public interface ChangeFilterMainNumber {
void OnChangeFilterMainNumberListener(int totalCheckedNumber);
}
ChangeFilterMainNumber listener;
FilterMainListAdapter(ChangeFilterMainNumber listener) {
this.listener = listener;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(listener != null) {
listener.OnChangeFilterMainNumberListener(position)
}
}
});
}
}
class FilterSubListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
}
来源:https://stackoverflow.com/questions/39408588/how-to-create-an-interface-between-an-adapter-and-a-viewholder