如何在ViewHolder中禁用onLongPressListener?

时间:2015-10-05 17:25:12

标签: android android-recyclerview android-viewholder

我正在尝试临时禁用我在适配器的ViewHolder中设置的onLongPressListener。我想禁用它,因为我想实现RecyclerView的拖放功能(允许用户重新排列项目)。

目前,长按监听器允许用户重命名项目,我希望当用户按下"重新排列"按钮(在工具栏中)我想禁用viewHolder的长按监听器并激活拖放功能。我不知道如何禁用在recyclerview的每个视图上设置的监听器。

这是我的适配器代码:

public class GroceryItemsAdapter extends RecyclerView.Adapter<GroceryItemsAdapter.ShoppingListViewHolder> {
private ArrayList<String> mItems;
private Context mContext;
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;
private MaterialDialog addItemdialog;
public static String nameOfList;

public GroceryItemsAdapter(Context context, ArrayList<String> items, SharedPreferences preferences, SharedPreferences.Editor editor, String nameOfList) {
    mItems = items;
    mContext = context;
    mSharedPreferences = preferences;
    mEditor = editor;
    this.nameOfList = nameOfList;
}

@Override
public ShoppingListViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
    View view = LayoutInflater.from(mContext).inflate(R.layout.shopping_list_item,viewGroup,false);
    ShoppingListViewHolder viewHolder = new ShoppingListViewHolder(view);

    return viewHolder;
}

@Override
public void onBindViewHolder(ShoppingListViewHolder shoppingListViewHolder, int position) {
    shoppingListViewHolder.bindShoppingList(mItems.get(position));
}

@Override
public int getItemCount() {
    return mItems.size();
}

public class ShoppingListViewHolder extends RecyclerView.ViewHolder implements CompoundButton.OnCheckedChangeListener, View.OnLongClickListener{
    public TextView mShoppingListItem;
    public CheckBox mCheckBox;
    public TextView mEmptyTextView;

    public ShoppingListViewHolder(View itemView) {
        super(itemView);
        mShoppingListItem = (TextView) itemView.findViewById(R.id.shoppingListItem);
        mCheckBox = (CheckBox) itemView.findViewById(R.id.shoppingListCheckBox);

        View rootView = ((Activity)mContext).getWindow().getDecorView().findViewById(android.R.id.content);

        mEmptyTextView = (TextView)rootView.findViewById(R.id.list_empty);
        mEmptyTextView.setVisibility(View.INVISIBLE);
        mCheckBox.setOnCheckedChangeListener(this);
        itemView.setOnLongClickListener(this);
    }
public void bindShoppingList(String item){
        mShoppingListItem.setText(item);
        mCheckBox.setChecked(false);
    }
}

1 个答案:

答案 0 :(得分:1)

在适配器上实现标记。

作为LongClickListener的第一行,检查标志。如果已设置,请不要执行长按操作。您不需要禁用侦听器,只需要阻止它包含的代码执行。