在 kotlin 的片段中弹出 window

Popup window in fragment in kotlin

我需要弹出窗口 window 来显示我的用户选项 例如,我想添加一个长按按钮,然后在单击该按钮时显示 具有透明背景的弹出窗口 window,在外部单击时关闭弹出窗口 window

exactly like this

我尝试了很多方法,但没有一个对我有用。

我也不知道如何使用对话框 window。

无论使用哪一个,dilog 片段或弹出 window 但我需要我的 window to be like this(on the top is user name which has given from data base and then options)

这里是我应该放置弹出窗口的地方 window:

val mUserAdapter = UserAdapter()
        mUserAdapter.setOnclickListener(AdapterListener({
            if (it != 0L)
                this.findNavController().navigate(
                    UserListFragmentDirections.actionUserListFragmentToIncreaseMoneyFragment(it)
                )
            Log.d("TAG", "navTeat $it ")
        }, {
            deleteDialog(it)
        }
        ) {
            Toast.makeText(activity, "Long", Toast.LENGTH_SHORT).show() //Here instead of Toast, I need POPUP WINDOW

        })

谢谢 :)

1.Dialog片段

假设您使用的是导航组件,请在 navGraph 中使用

标记添加 dialogFragment,

<dialog
    android:id="@+id/navigation_dialog_fragment"
    android:name="com.app.example.ui.dialogFragment"
    tools:layout="@layout/dialogFragment"/>

覆盖对话框片段的 onCreate() 使背景半透明,

class mDialogFrag: DialogFragment(R.layout.dialog_fragment) {

   override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
         setStyle(STYLE_NO_FRAME, R.style.DialogTheme)

         //populate UI with data from DB

对话框主题:

<style name="AppDialogTheme" parent="Theme.AppCompat.Light">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">#40000000</item><!--dialog background-->
    <item name="android:backgroundDimEnabled">true</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
</style>

2.Alert对话框

在你的目标片段中,

lateinit var mAlert : AlertDialog
//inflate custom layout
val alertBinding = AlertBinding.inflate(LayoutInflater.from(requireContext()))
alertBinding?.apply{
  //populate UI with data from DB
}
val builder = AlertDialog.Builder(requireContext())
mAlert = builder.setView(alertBinding.root)
             .setCancelable(false)
             .create()
mAlert.window?.setBackgroundDrawable(
     ContextCompat.getDrawable(requireContext(),R.drawable.bg_card) //custom dialog background 
)
mAlert.show()

这两种方法都使用自定义布局来实现您的要求。 但 DialogFragment 用于更复杂的 UI(即动态地提供对 UI 的更多控制)。 而 AlertDialog 可用于更简单的 UI,例如您的

或者你可以使用默认的单选列表AlertDialog,比如here,这样更简单。