首页 > 解决方案 > kotlin片段中的弹出窗口

问题描述

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

就像这样

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

我也不知道如何使用对话窗口。

无论使用哪个,dilog 片段或弹出窗口,但我需要我的窗口是这样的(顶部是从数据库给出的用户名,然后是选项)

这是我应该在哪里放置弹出窗口:

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

        })

谢谢 :)

标签: androidkotlinandroid-alertdialogandroid-dialogfragmentpopupwindow

解决方案


1.对话框片段

假设您正在使用导航组件,请在 navGraph 中使用 <dialog> 标签添加 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.警报对话框

在您的目标片段中,

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,例如您的 UI。

或者您可以使用默认列表,称为传统的单选列表,AlertDialog这里这样更简单。


推荐阅读