简体   繁体   English

单击recyclerview的项目时如何创建对话框?

[英]How to create dialog box when click on the item of recyclerview?

I'm trying to create a function that once a user clicks on the recycler view, a dialog box will pop out but I am stuck on the error as mentioned below.我正在尝试创建一个 function ,一旦用户单击回收站视图,就会弹出一个对话框,但我遇到了如下所述的错误。 When I try to initialize AlertDialog.build and put this as the parameter, it shows an error.当我尝试初始化 AlertDialog.build 并将this作为参数时,它显示错误。 I had tried with a few other parameters like context, getActivity.我曾尝试使用其他一些参数,例如上下文、getActivity。 But the error is still the same.但错误仍然相同。

enter image description here在此处输入图像描述

The code below is my full code下面的代码是我的完整代码

package com.example.tuitioncentre;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Observable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.firestore.DocumentSnapshot;

public class myadapter_tutorlist extends FirebaseRecyclerAdapter<User,myadapter_tutorlist.myviewholder> {

    AlertDialog.Builder builder;


    public myadapter_tutorlist(@NonNull FirebaseRecyclerOptions<User> options) {
        super(options);
    }

    @Override
    protected void onBindViewHolder(@NonNull final myviewholder holder, int position, @NonNull final User model) {

        holder.name.setText("Tutor's Name:" + model.getUsername());
        holder.phone.setText("Phone No:" + model.getPhone());
        holder.email.setText("Email:" + model.getEmail());
        holder.status.setText("Status: " + model.getActive().toString());
        builder = new AlertDialog.Builder(this);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                //Toast.makeText(v.getContext(),model.getUsername(),Toast.LENGTH_SHORT).show();

                builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);
                builder.setMessage("Do you want to activate tutor account ?")
                        .setCancelable(false)
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Toast.makeText(v.getContext(),"you choose yes action for alertbox", Toast.LENGTH_SHORT).show();
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                //  Action for 'NO' Button
                                dialog.cancel();
                                Toast.makeText(v.getContext(),"you choose no action for alertbox", Toast.LENGTH_SHORT).show();
                            }
                        });
                //Creating dialog box
                AlertDialog alert = builder.create();
                //Setting the title manually
                alert.setTitle("AlertDialogExample");
                alert.show();
            }
        });
    }
    @NonNull
    @Override
    public myviewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //put singlerow xml into view holder
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.singlerow,parent,false);
        return new myviewholder(view);
    }


    class myviewholder extends RecyclerView.ViewHolder{
        TextView name,phone,email,status;
        public myviewholder(@NonNull View itemView) {
            super(itemView);
            name=(TextView)itemView.findViewById(R.id.nametext);
            phone=(TextView)itemView.findViewById(R.id.phonetext);
            email=(TextView)itemView.findViewById(R.id.emailtext);
            status=(TextView)itemView.findViewById(R.id.statustext);
        }
        
    }
}

Passing "this" to AlertDialog.Builder(this);将“this”传递给AlertDialog.Builder(this); won't work as you're trying to pass a reference of your Adapter.当您尝试传递适配器的引用时将不起作用。

There are two correct ways to achieve this:有两种正确的方法可以实现这一点:

Add a variable to reference your Activity like Activity mActivity;添加一个变量来引用您的活动,例如Activity mActivity; in your Adapter class.在您的适配器 class 中。 Then, in your Activity class where you're initializing the Adapter, you can pass your activity context as "this".然后,在您初始化适配器的活动 class 中,您可以将活动上下文作为“this”传递。 You can achieve it either with a constructor in the Adapter class or in your Activity class use your adapter instance once it is initialized to access the mActivity variable and set it.您可以使用适配器 class 或活动 class 中的构造函数来实现它,一旦初始化访问mActivity变量并设置它,就使用adapter实例。

Alternatively, you can use a view interface and implement it in your activity, override the method to show the AlertDialog in your activity.或者,您可以使用视图接口并在您的活动中实现它,覆盖该方法以在您的活动中显示 AlertDialog。 Then add a reference variable of that interface in your Adapter like SomeInterface mInfterface;然后在您的适配器中添加该接口的引用变量,例如SomeInterface mInfterface; and initialize it in your Activity class the same way mentioned above.并以上述相同的方式在您的活动 class 中对其进行初始化。 Then you can just call that method to show the AlertDialog and pass the data to that method from the Adapter to show all information like -然后您可以调用该方法来显示 AlertDialog 并将数据从适配器传递给该方法以显示所有信息,例如 -

mInterface.showAlertDialog(model);

First pass the context from the Activity or Fragment:首先从 Activity 或 Fragment 传递context

For activity:对于活动:

myadapter_tutorlist(options, this);

For Fragment:对于片段:

myadapter_tutorlist(options, getActivity());

Then create a Context variable in side the Adapter class:然后在 Adapter class 中创建一个上下文变量:

public class myadapter_tutorlist extends FirebaseRecyclerAdapter<User,myadapter_tutorlist.myviewholder> {

    AlertDialog.Builder builder;
    Context context;


    public myadapter_tutorlist(@NonNull FirebaseRecyclerOptions<User> options) {
        super(options);
        this.context = context;
    }

Now you can pass this context to your AlertDialog现在您可以将此上下文传递给您的 AlertDialog

builder = new AlertDialog.Builder(context);

Then should work.然后应该工作。

Happy coding:)快乐编码:)

first create this class:首先创建这个 class:

class RecyclerItemClickListener extends RecyclerView.SimpleOnItemTouchListener {
interface OnRecyclerClickListener{
    void onItemClick(View view, int position);
}

private final OnRecyclerClickListener mListener;
private final GestureDetectorCompat mGestureDetector;


public RecyclerItemClickListener(Context context, final RecyclerView recyclerView,
                                 OnRecyclerClickListener listener) {
    mListener = listener;

    mGestureDetector = new GestureDetectorCompat(context, new GestureDetector.SimpleOnGestureListener(){
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
          View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
            if (childView != null && mListener != null){
                Log.d(TAG, "onSingleTapUp: calling listener.onItemClick");
                mListener.onItemClick(childView, recyclerView.getChildAdapterPosition(childView));
            }
            return true;
        }
});
}

@Override
public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
    if (mGestureDetector != null){
        boolean result = mGestureDetector.onTouchEvent(e);
        return result;
    } else {
        return false;
    }
}
}

and in MainActivity:在 MainActivity 中:

in onCreate method: first define recyclerView variable by findviewbyid() then:在 onCreate 方法中:首先通过 findviewbyid() 定义 recyclerView 变量,然后:

        recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerView, this));

then implement onItemClick() method.然后实现 onItemClick() 方法。 you can define alert dialog here:您可以在此处定义警报对话框:

@Override
public void onItemClick(View view, int position) {
    Toast.makeText(this, "normal tap on position " + position, Toast.LENGTH_SHORT).show();

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM