In my code, dialog.dismiss();
function not working but callback function working perfectly, callback.onItemClicked(position);
Please help me, I’m new in the android field!
The same code working fine in activity
, but problems arrive in the adapter class
.
Adapter Class
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
private final Context mContext;
private final ArrayList<String> mData;
AdapterCallback callback;
Dialog dialog;
public Adapter(Context mContext, ArrayList<String> mData, AdapterCallback callback) {
this.mContext = mContext;
this.mData = mData;
this.callback = callback;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item, parent, false));
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
if (Helper.readSharedPref(mContext, Constants.PREF_KEY_Sub).equalsIgnoreCase("notActive")) {
if (!mData.get(position).equalsIgnoreCase("PENDING")) {
alertSuccessShowDialog(mContext, position);
}
}
}
@Override
public int getItemCount() {
return mData != null ? mData.size() : 0;
}
@Override
public int getItemViewType(int position) {
return position;
}
public interface AdapterCallback {
void onItemClicked(int position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tv_bank_name;
public ViewHolder(@NonNull View itemView) {
super(itemView);
tv_bank_name = itemView.findViewById(R.id.tv_bank_name);
}
}
private void alertSuccessShowDialog(Context context, int position) {
dialog = new Dialog(context);
dialog.setContentView(R.layout.enquiry_popup);
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.getWindow().setGravity(Gravity.CENTER);
dialog.setCancelable(false);
dialog.findViewById(R.id.iv_close_btn).setOnClickListener(v -> {
dialog.dismiss();
callback.onItemClicked(position);
});
dialog.show();
}
}
3
Answers
You have to change your code. Because you can’t dismiss the dialog before showing it. So change your code like this.
What @Dev4life said is right you have to call after create the dialog, and you should use AlertDialog instead of Dialog because of security reasons i believe. There is a brief statement in the Documentation about:
Dialogs
Here is my code dunno, but should work:
This is my last bet, dunno know how to fix.
Create a class for your dialog and if needed pass the Context in the Constructor.
And inside of your Adapter, maybe you will need to pass the fragment manager in the adapter, but i dunno if this is right, i’m new in android:
new DialogEnquiry(callback, position).show(fragmentManager, "dialog");
This is my last attempt, i hope this can give you some insight.
Good Lucky!
Nothing wrong with your dialog box method code, just change calling method like this with new context…