Search code examples
androidandroidxandroid-actionmode

ActionMode menu icon is not shown


I am trying setup contextual action bar when long click on a item in a recyclerview. But menu icon is not shown.

action mode without icons shown

Code is given below.

listAdapter.setOnItemClickListener(object : OnItemClickListener {

            override fun onItemClick(position: Int) {
               ...
            }

            override fun onItemLongClick(position: Int): Boolean {

                if (actionMode != null) {
                    return false
                }

                val activity = activity as AppCompatActivity
                actionMode = activity.startSupportActionMode(actionModeCallback)


                return true
            }

        })

Action Mode callback

internal val actionModeCallback = object : ActionMode.Callback {

    override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean {
        when (item?.itemId) {
            R.id.item_delete -> {
                actionMode?.finish()
                return true
            }
        }
        return false
    }

    override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
        actionMode?.menuInflater?.inflate(R.menu.menu_context, menu)
        actionMode?.title = "delete"

        return true
    }

    override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean {

        return false
    }

    override fun onDestroyActionMode(mode: ActionMode?) {
        actionMode = null
    }
}

menu_context.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/item_delete"
        android:title="@string/menu_option_text_delete"
        android:icon="@drawable/ic_delete_white_24dp"
        app:showAsAction="always"
        />
</menu>

What I tried?

Did not work, even the action mode title is not shown.

I am using androidx, appCompat version : 1.1.0-rc01

Please help!


Solution

  • Actually this was a mistake in my part as pointed out in the issue tracker

    override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
         /*-->*/mode?.menuInflater?.inflate(R.menu.menu_context, menu)
         return true
    }
    

    Note that you should use the passed in mode and not your own ActionMode object to get the correct inflater.