I tried to make a PopupMenu
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
menu_btn.setOnClickListener {
var menu: PopupMenu?
menu = PopupMenu(this.context, it)
menu.inflate(R.menu.card_menu)
menu.setOnMenuItemClickListener {
when(it.itemId) {
R.id.menu_modify -> { Toast.makeText(context, "Modify", Toast.LENGTH_LONG).show()
true }
R.id.menu_delete -> { Toast.makeText(context, "Delete", Toast.LENGTH_LONG).show()
true }
else -> false
}
}
menu.show()
}
}
but I get wiggly red line under
menu = PopupMenu(this.context, it)
That says: Type mismatch. Required: Context Found: Contex?
and even when I use !! - I get this error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.emek1.myapplication.FragmentOne.onCreate(FragmentOne.kt:24)
at android.support.v4.app.Fragment.performCreate(Fragment.java:2414)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1418)
at android.support.v4.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1195)
at android.support.v4.app.FragmentTransition.calculateFragments(FragmentTransition.java:1078)
at android.support.v4.app.FragmentTransition.startTransitions(FragmentTransition.java:117)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2408)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2243)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:654)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:146)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1244)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1092)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1622)
Note: that it's not in MainActivity.kt It's a Fragment.
Write this code
context?.let {
menu = PopupMenu(it, view)
}
Here view will be your anchor view of the popup.
instead of
menu = PopupMenu(this.context, it)
If it was a fragment you should call context like this.
menu = PopupMenu(activity!!, it)
or if you have the latest library you can do something like this
menu = PopupMenu(requireActivity(), it)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With