片段中上下文菜单项的警报对话框未显示任何内容

时间:2020-04-22 23:33:50

标签: android-fragments kotlin android-alertdialog contextmenu

首先,我正在使用Navigation Drawer Activity来显示一些片段,当试图在片段中显示上下文菜单时,它不会显示为上下文,而只会显示为选项菜单。然后我尝试按原样使用它(一个选项菜单),但是虽然我在一个活动上尝试了该方法,但该方法仍然完美运行,但它没有显示我的警报对话框

这是main.xml菜单文件

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/action_settings"
    android:title="@string/action_settings" />

这是我的fragment.kt文件

override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenu.ContextMenuInfo?) {
    menu.add(0, v.getId(), 0, "action_settings")
}

override fun onContextItemSelected(item: MenuItem): Boolean {
    if (item.getItemId() == R.id.action_settings) {
        val dialog = AlertDialog.Builder(getContext())
        dialog.setTitle("Enter Bookmark Name")
        val factory = LayoutInflater.from(this.getContext())
        val view: View = factory.inflate(layout.alertlayout, null)
        dialog.setView(view)
        val alert = dialog.create()
        alert.show()
    }

    return true;
}

这是我尝试将代码应用于一项活动的尝试,该活动对我有用

class Test : AppCompatActivity() {

lateinit var pdf: PDFView
lateinit var Btn1: Button
var ac1 = 0

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_test)

    pdf = findViewById(R.id.Viewer1)
    Btn1 = findViewById(R.id.Btn)
    pdf.fromAsset("01P1.pdf")
        .defaultPage(ac1)
        .enableSwipe(true)
        .scrollHandle(CustomScrollHandle(this))
        .swipeHorizontal(false)//set horizontal swipe to false
        .enableDoubletap(true)//double tap to zoom
        .load()

    registerForContextMenu(Btn1)
}

override fun onContextItemSelected(item: MenuItem): Boolean {
    val dialog = AlertDialog.Builder(this)
    dialog.setTitle("Enter Bookmark Name")
    val factory = LayoutInflater.from(this)
    val view: View = factory.inflate(R.layout.alertlayout, null)
    dialog.setView(view)
    val alert = dialog.create()
    alert.show()
    return true;
}

override fun onCreateContextMenu(menu: ContextMenu?, v: View?, menuInfo: ContextMenu.ContextMenuInfo?) {
    if (menu != null) {
        if (v != null) {
            menu.add(0, v.getId(), 0, "action_settings")
        }
    }
}

那么,我的代码怎么了?

0 个答案:

没有答案