I\'m using RecyclerView
to list some text and now I want to make it so that when the user clicks on text a custom Alert Dialog box pops up.
I have tried
This is not the answer for your query but the better way to handle this scenario.
Use callback methods.
In your Activity:
This will implement the interface that we have in our Adapter
. In this example, it will be called when the user clicks on an item in the RecyclerView
.
public class MyActivity extends Activity implements AdapterCallback {
private MyAdapter mMyAdapter;
@Override
public void onMethodCallback() {
// Show your alert
}
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mMyAdapter = new MyAdapter(this);
}
}
In your Adapter:
In the Activity, we initiated our Adapter
and passed this as an argument to the constructor. This will initiate our interface for our callback method. You can see that we use our callback method for user clicks.
public class MyAdapter extends RecyclerView.Adapter {
private AdapterCallback mAdapterCallback;
public MyAdapter(Context context) {
try {
this.mAdapterCallback = ((AdapterCallback) context);
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement AdapterCallback.");
}
}
@Override
public void onBindViewHolder(final MyAdapter.ViewHolder viewHolder, final int i) {
// simple example, call interface here
// not complete
viewHolder.itemView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
mAdapterCallback.onMethodCallback();
} catch (ClassCastException exception) {
// do something
}
}
});
}
public static interface AdapterCallback {
void onMethodCallback();
}
}
Courtesy : Call Activity method from adapter