我试图制作一个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()
}
}
但是我在
下出现了模糊的红线menu = PopupMenu(this.context, it)
说: 类型不匹配。 需要: 语境 发现: 孔蒂?
甚至当我使用! -我收到此错误
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)
注意:它不在MainActivity.kt中 这是一个片段。
答案 0 :(得分:2)
NullPointerException
源自onCreate()
在onCreateView()
之前运行,这夸大了视图层次。因此menu_btn
仍然为空,因为未找到。再看看Fragments的生命周期。
对于弹出窗口,最好使用Context
参数View
中的it.context
。
答案 1 :(得分:1)
编写此代码
context?.let {
menu = PopupMenu(it, view)
}
这里视图将成为弹出窗口的锚点视图。
代替
menu = PopupMenu(this.context, it)
答案 2 :(得分:0)
如果它是片段,则应这样调用上下文。
menu = PopupMenu(activity!!, it)
或者如果您拥有最新的库,则可以执行以下操作
menu = PopupMenu(requireActivity(), it)