I\'m using RecyclerView
with CardView
and inside the CardView
have 2 buttons. Now, have implemented the onClick
events by imp
Please, try this principle to create a communication between activity, adapter through the interface, I hope this principle helps you:
Model Class:
public class YourModel {
private String firstName;
private String lastName;
public YourModel(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
//... setters & getters
}
Interface:
public interface AdapterCallback {
void onClickCallback(YourModel itemModel);
}
Adapter:
public class YourAdapter extends RecyclerView.Adapter {
private List data;
private AdapterCallback callback;
private Context context;
public YourAdapter(List data, AdapterCallback callback) {
this.data = data;
this.callback = callback
}
@Override
public YourAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View item = inflater.inflate(R.layout.item_recycler, parent, false);
return new ViewHolder(item);
}
@Override
public void onBindViewHolder(YourAdapter.ViewHolder holder, int position) {
YourModel itemModel = data.get(position);
String lastName = itemModel.getLastName();
String firstName = itemModel.getFirstName();
holder.tvFirstName.setText(firstName);
holder.tvLastName.setText(lastName);
holder.tvFirstName.setOnClickListener {
callback.onClickCallback(itemModel));
}
}
@Override
public int getItemCount() {
return data.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
private TextView tvFirstName;
private TextView tvLastName;
ViewHolder(View itemView) {
super(itemView);
tvFirstName = (TextView) itemView.findViewById(R.id.tv_first);
tvLastName = (TextView) itemView.findViewById(R.id.tv_last);
}
}
Activity:
public class MyActivity extends AppCompatActivity implements AdapterCallback {
private YourAdapter adapter;
private List items;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 1. init your list && fill it with needed data
// 2. init your adapter
// 3. put your list as parameter into constructor + interface
items = new ArrayList()
items.add(YourModel("John", "Doe"));
items.add(YourModel("Bob", "Marley"));
adapter = new YourAdapter(items, this)
}
@Override
public void onClickCallback(YourModel itemModel) {
Toast.makeText(this, itemModel.getFirstName(), Toast.LENGTH_SHORT).show();
}
I think that this information is enough to understand what I mean. The same principle you can create multiple OnClick methods in your interface or put one onClick for a few buttons and check id or something else to get needed information that you need. Good luck