如何使RecyclerView的项目不可点击?

时间:2015-11-27 06:26:48

标签: android android-recyclerview

我尝试了以下代码:

{{1}}

第一行禁用单击的当前视图。点击一下后,我想设置所有不可点击的项目,这样就不会发生双击。 似乎第二行无效。

4 个答案:

答案 0 :(得分:2)

尝试view.setClickable(false);在您不希望被点击的视图上

答案 1 :(得分:1)

第一个简单选项

但是使用系统时间实际上会很糟糕:

 long mLastClickTime = 0;

    youradapter.setOnItemClickListener(new youradapter.OnItemClickListener() {
        @Override
        public void onItemClick(int position) {

            if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
                return;
            }
            mLastClickTime = SystemClock.elapsedRealtime();

            ....//your code


        }
    });

但是对于干净的编程,我建议这样做:

有点棘手,但很简单

在您的适配器中引入一个布尔变量,请注意viewHolder()和onBindViewHolder()方法:

private boolean clickable = true;


@Override
public void onBindViewHolder(@NonNull myAdapter.ViewHolder viewHolder, int position) {

    if (!clickable){
        viewHolder.cardView.setClickable(false);
    } else {
        viewHolder.cardView.setClickable(true);
    }

    //....
}

public void setClickable(boolean clickable) {
    this.clickable = clickable;
    myadapter.notifyDataSetChanged();
}

public static class ViewHolder extends RecyclerView.ViewHolder {

    CardView cardView;

    public ViewHolder(View itemView, final myViewHolder.OnItemClickListener listener){
        super(itemView);
        //..

        cardView = itemView.findViewById(R.id.cardView);

        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) {
                        listener.onItemClick(position);
                    }
                }
            }
        });
    }
}

并根据需要使用myadapter.setClickable(state)

像这样:

    youradapter.setOnItemClickListener(new youradapter.OnItemClickListener() {
        @Override
        public void onItemClick(int position) {

            myadapter.setClickable(false);

            ....//your code


        }
    });

,也许在您的onResume()中:

 myadapter.setClickable(true);

答案 2 :(得分:1)

您可以通过重写下面的方法并返回true来防止viewGroup子项的触摸;

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    return true;
}

答案 3 :(得分:0)

在您的recyclerView适配器中,您将获得如下方法:

@Override
public YourViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View partnerTypeView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
    return new YourViewHolder(partnerTypeView);
}

添加以下行:

    @Override
    public YourViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View partnerTypeView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
        partnerTypeView.setClickable(false);//This is line that make row non clickable
        return new YourViewHolder(partnerTypeView);
    }

如果这不起作用,请在下方评论