2015-10-05 27 views
1

我想臨時禁用onLongPressListener,我在我的適配器的ViewHolder中設置。我想禁用它,因爲我想實現RecyclerView的拖放功能(以允許用戶重新排列項目)。如何禁用ViewHolder中的onLongPressListener?

目前,長按聽衆允許用戶重命名一個項目,我想當用戶按下「重新排列」按鈕(在工具欄中)我想禁用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); 
    } 
} 
+0

使用一個標誌來啓用/禁用長按監聽器,當點擊工具欄按鈕時激活標誌並在完成拖放功能時禁用標誌。 –

+0

是的,嘗試過,但這並沒有訣竅,因爲我在創建適配器時設置了點擊監聽器,並且如果在此之後我無法禁用。改變旗子後,我試圖改變notifydataset並且它也沒有工作。 –

回答

2

您的適配器上實現的標誌。

作爲LongClickListener的第一行,請檢查標誌。如果已設置,請勿執行長按操作。您不需要禁用偵聽器,只需要防止其包含的代碼執行。

+0

謝謝你的建議。儘管我認爲我通過禁用監聽器來做到這一點,但我可能會將其改變爲此,因爲它是實現相同目標的更明智的方式。 –