如何禁用 Android 中的 RecyclerView 项目?

How to disable RecyclerView items in Android?

Textviews 和 Checkboxes 在 Recyclerview 中。最初选中所有复选框。我想阻止用户更改复选框状态,但我不想阻止 Recyclerview 滚动。我想在我的片段 class 中而不是在适配器 class.

中执行此操作

如何防止用户更改复选框状态?

下面是适配器class中onBindViewHolder写的示例代码。

holder.cbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            //set your object's last status
            tblFilm.setSelected(isChecked);
        }
    });

The above code used for first mode which allows user clicks on checkbox.

After that I have second mode where I do not want to get clicked on checkbox at all.

我所做的如下。

optionsoff(recyclerView);
private static void optionsOff(ViewGroup layout) {
        layout.setEnabled(false);
        layout.setClickable(false);
        for (int i = 0; i < layout.getChildCount(); i++) {
            View child = layout.getChildAt(i);
            if (child instanceof ViewGroup) {
                optionsOff((ViewGroup) child);
            } else {
                child.setEnabled(false);
                child.setClickable(false);
            }
        }

我猜这个 optionsoff() 不起作用。因为它没有禁用复选框。我仍然可以点击复选框。我需要有关禁用 Recyclerview 项目的第二种方法的帮助。

每个 CheckBox 都有方法 setEnabled

onBindViewHolder 中,您可以获得对所需复选框的引用并禁用它。

像这样:

public void onBindViewHolder(ViewHolder holder, final int position) {
    holder.checkBox.setEnabled(data.get(position).isEnabled());
}

下面的答案也是通过 xml 的工作解决方案。

可以试试这样的东西吗?

<CheckBox
        android:id="@+id/server_is_online"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:checked="true"
        android:clickable="false"
        android:text="@string/server_is_online"
        android:textSize="23sp" />

您可以在您的适配器(扩展 BaseAdapter)中以编程方式添加

public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;
        if (convertView == null) {
            LayoutInflater inflator = context.getLayoutInflater();
            view = inflator.inflate(R.layout.rowbuttonlayout, null);
            final ViewHolder viewHolder = new ViewHolder();
            viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
        } else {
            view = convertView;
            ((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
        }
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.checkbox.setChecked(true);
        holder.checkbox.setEnabled(false);
}

class 的好例子扩展了 BaseAdapter here