Search code examples
androidkotlinpopupmenu

Weird in popup menu


I have created a menu icon on action bar. When it is clicked, I expect it will show something like this

enter image description here

But it display on the left hand side instead.

enter image description here

What could be this issue ?

 override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
        inflater!!.inflate(R.menu.fragment_menu, menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
            val id = item.getItemId()
            if (id == R.id.more) {
                var popup: PopupMenu? = PopupMenu(context!!, view!!)
                popup?.menuInflater?.inflate(R.menu.pop_up_menu, popup.menu)
                popup?.show()

                popup?.setOnMenuItemClickListener({ item: MenuItem? ->
                    when (item!!.itemId) {
                        R.id.logOut -> {
                        }
                    }
                    true
                })
            } else
                super.onOptionsItemSelected(item)

            return true
        }

fragment_menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/more"
          android:title="menu"
          app:showAsAction="always"
          android:icon="@drawable/ic_more"/>
</menu>

pop_up_menu

<?xml version="1.0" encoding="utf-8"?>
<menu
        xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
            android:id="@+id/logOut"
            app:showAsAction="always"
            android:title="Log Out"
    />

</menu>

The view I passing is this

@Nullable
    public View getView() {
        return this.mView;
    }

Solution

  • You are passing the wrong view as what @CodeRed mentioned.

    Replace

    var popup: PopupMenu? = PopupMenu(context!!, view!!)
    

    to

    val vItem = getActivity().findViewById<View>(R.id.more)
    var popup: PopupMenu? = PopupMenu(context!!, vItem)