Call Custom Dialog In Adapter Class
I have created a simple Custom dialog class and I want to display it after clicking on a row in RecycleView. My dialog class looks: public class AddToQueueDialog extends Dialog imp
Solution 1:
Just pass the context
of your current Activity
to your Adapter
class and use it when you are creating an instance of AddToQueueDialog
.
For example:
MainActivity.java
publicclassMainActivityextendsAppCompatActivity {
Context mContext;
// Views
RecyclerView mRecyclerView;
// Values
List<Recipe> mRecipeList;
// Adapter
RecipeAdapter mAdapter;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
// Views
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
.................
..........................
// Values
mRecipeList = newArrayList<Recipe>();
// Adapter
mAdapter = newRecipeAdapter(mContext, mRecipeList);
// Set adapter to RecyclerView
mRecyclerView.setAdapter(mAdapter);
.................
..........................
}
}
RecipeAdapter.java
publicclassRecipeAdapterextendsRecyclerView.Adapter<RecipeAdapter.ViewHolder> {
Context mContext;
LayoutInflater mInflater;
// List
List<Recipe> mRecipeList;
publicGroupListAdapter(Context context, List<Recipe> listRecipe) {
this.mContext = context;
this.mRecipeList = listRecipe;
mInflater = LayoutInflater.from(mContext);
}
.....................
...............................
publicclassViewHolderextendsRecyclerView.ViewHolder implementsView.OnClickListener {
publicViewHolder(View itemView) {
super(itemView);
info = (TextView) itemView.findViewById(R.id.textView);
favorite = (Button) itemView.findViewById(R.id.addToFav);
favorite.setOnClickListener(this);
info.setOnClickListener(this);
}
@OverridepublicvoidonClick(View v) {
if(v.getId() == info.getId()){
AddToQueueDialogaddToQueueDialog=newAddToQueueDialog(mContext);
addToQueueDialog.show();
}
}
}
............
......................
}
Hope this will help~
Solution 2:
classMyAdapterextendsRecyclerView.Adapter<VH> {
// set this field through setter or constructorprivate OnClickListener mMyOnClickListener;
...
voidonBindViewHolder(..., VH viewHolder) {
viewHolder.rootView.setOnClickListener(() -> {
if (mOnClickListener != null) {
mOnClickListener.onClick();
}
});
}
staticclassVHextendsViewHolder {
View rootView;
VH(View itemView) {
super(itemView);
rootView = itemView;
}
}
}
classMainActivityextendsAppCompatActivity {
...
voidsetUpRecyclerView(){
...
adapter.setMyOnClickListener(() -> {
newDialog(MainActivity.this).show();
});
}
}
Post a Comment for "Call Custom Dialog In Adapter Class"