Rolanddev
Rolanddev

Reputation: 59

Show AlertDialog when clicking an item of RecyclerView

I click on an item of a RecyclerView to display a dialog box but I get the error when clicking on the item.

The specified child already has a parent. You must call removeView() on the child's parent first.

Here is my code:

holder.itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        final Intent intent = new Intent(v.getContext(), AddMestAct.class);
        intent.putExtra("photo_url", model.getPhoto());
        intent.putExtra("ID", model.getReparsId());
        intent.putExtra("RestId", model.getRestoId());
        intent.putExtra("prix", model.getPrix());
        intent.putExtra("nomresto", model.getNomRepars());
        //v.getContext().startActivity(intent);

        final AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());
        final View view1 = LayoutInflater.from(v.getContext()).inflate(R.layout.customdialog, null);
        final EditText input = (EditText) view1.findViewById(R.id.password);
        Button btn_cancel = (Button) view1.findViewById(R.id.btncancel);
        Button btn_modifie = (Button) view1.findViewById(R.id.btnok);
        TextView MontreNomRepars = (TextView) view1.findViewById(R.id.txt);
        MontreNomRepars.setText(model.getNomRepars());
        alert.setView(v);
        final AlertDialog alertDialog = alert.create();
        alertDialog.setCanceledOnTouchOutside(false);

        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });

        btn_modifie.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(view1.getContext(), "Code erroné", Toast.LENGTH_SHORT).show();
            }
        });

        alertDialog.show();
    }
});

The line which throws the error is:

alertDialog.show();

Upvotes: 0

Views: 128

Answers (2)

Sam Chen
Sam Chen

Reputation: 8867

Change alert.setView(v) to alert.setView(view1).

Variable naming is important. You should treat it seriously.

Upvotes: 1

miladev95
miladev95

Reputation: 44

set attachToRoot false when inflating your view in adapter

like this

View view = LayoutInflater.from(context).inflate(R.layout.item_blocked, parent, false);

Upvotes: 0

Related Questions