Monday, 16 September 2013

Not allow the action mode to be removed

The action mode contains extra buttons that are shown on a specific context, for example, when the user has selected an item. By default, when the user clicks on the Done button, it dissapears, but there is a way to not allow it to do so.

It is based on this post, which try to capture the done button. In the click listener, it try to to call a method. If it returns false, it creates a new actionMode and set a new Click Listener.

doneButton = findViewById(doneButtonId);
doneButton.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        if (updateExpense(newExpense)) {
   // Close the drawer
     if (mDrawerLayout.isDrawerOpen(mRightLinearDrawer)) {
     mDrawerLayout.closeDrawer(mRightLinearDrawer);
     }
     } else {
     // Show the action mode again
editActionMode = startActionMode(new EditExpenseActionMode());
// Reassign the done button
doneButton = findViewById(doneButtonId);
doneButton.setOnClickListener(this);
   }
}

The key point is in the last block. When the method updateExpense returns false, it creates a new actionMode. Because the new actionMode has another done button, it find it and set the on click listener as itself.

Source code:
https://github.com/jiahaoliuliu/MyExpenses/blob/master/src/com/jiahaoliuliu/android/myexpenses/MainActivity.java

No comments:

Post a Comment