无法使用 Kotlin 从自定义对话框获取文本

问题描述 投票:0回答:1

我有一个自定义对话框,要求两个文本输入,我的目标是在按下对话框的“确定”选项时从文本视图中获取文本,但到目前为止我什至无法访问名为 userName 的文本视图,我可以'不明白我做错了什么。使用下面的代码我收到此错误“@layout/dialog_create_task_type 不包含带有 id userName 的声明”

这是我的DialogFragment:

class TaskTypeCreationDialog : DialogFragment() {

    internal lateinit var listener: TaskTypeCreationDialogListener

    interface TaskTypeCreationDialogListener {
        fun onDialogPositiveClick(dialog: DialogFragment, taskName: String)
        fun onDialogNegativeClick(dialog: DialogFragment)
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return activity?.let {
            val builder = AlertDialog.Builder(it)
            // Get the layout inflater.
            val inflater = requireActivity().layoutInflater;
            val inflatedView = inflater.inflate(R.layout.dialog_create_task_type, null)
            // Inflate and set the layout for the dialog.
            // Pass null as the parent view because it's going in the dialog
            // layout.
            val userName = inflatedView.findViewById<TextView>(R.id.userName)

            builder.setView(inflatedView)
                // Add action buttons.
                .setPositiveButton("ok"
                ) { dialog, id ->
                    listener.onDialogPositiveClick(this, "test")
                    dialog?.cancel()
                }
                .setNegativeButton("cancel"
                ) { dialog, id ->
                    getDialog()?.cancel()
                }
            builder.create()
        } ?: throw IllegalStateException("Activity cannot be null")
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        // Verify that the host activity implements the callback interface.
        try {
            // Instantiate the NoticeDialogListener so you can send events to
            // the host.
            listener = context as TaskTypeCreationDialogListener
        } catch (e: ClassCastException) {
            // The activity doesn't implement the interface. Throw exception.
            throw ClassCastException((context.toString() +
                    " must implement NoticeDialogListener"))
        }
    }


}

这是我的 xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/username"
        android:inputType="textEmailAddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginBottom="4dp"
        android:hint="first text" />
    <EditText
        android:id="@+id/password"
        android:inputType="textPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginBottom="16dp"
        android:fontFamily="sans-serif"
        android:hint="second text"/>
</LinearLayout>

我也尝试过使用绑定,但随后它崩溃了 “java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.lang.CharSequence android.widget.TextView.getText()” ” 使用代码:

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return activity?.let {
            val builder = AlertDialog.Builder(it)
            // Get the layout inflater.
            val inflater = requireActivity().layoutInflater;
            // Inflate and set the layout for the dialog.
            // Pass null as the parent view because it's going in the dialog
            // layout.
            val v = inflater.inflate(R.layout.dialog_create_task_type, null)
            builder.setView(v)
                // Add action buttons.
                .setPositiveButton("ok",
                    DialogInterface.OnClickListener { dialog, id ->
                        val binding = TaskTypeLayoutBinding.bind(v)
                        listener.onDialogPositiveClick(this, binding.userName.text.toString())
                        dialog?.cancel()
                    })
                .setNegativeButton("cancel",
                    DialogInterface.OnClickListener { dialog, id ->
                        getDialog()?.cancel()
                    })
            builder.create()
        } ?: throw IllegalStateException("Activity cannot be null")
    }```
android kotlin data-binding dialog android-dialogfragment
1个回答
0
投票

我发现我的错误是坚持在 onCreateDialog() 上获取 TextView,现在我已将此逻辑移至 onViewCreated() 我没有问题获取我需要的视图,我不确定我的错误会帮助任何人,但无论如何我都会留下我的问题以防万一。

我对代码做了一些更改,现在是这样的:

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val inflater = requireActivity().layoutInflater;
    val inflatedView = inflater.inflate(R.layout.dialog_create_task_type, null)
    // Inflate and set the layout for the dialog.
    // Pass null as the parent view because it's going in the dialog
    // layout.
return inflatedView
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    binding = DialogCreateTaskTypeBinding.bind(view)
    setupClickListeners(view)
}

private fun setupClickListeners(view: View) {
    val builder = activity?.let { AlertDialog.Builder(it) }
    if (builder != null) {
        builder.setView(view)
            // Add action buttons.
            .setPositiveButton("ok"
            ) { dialog, id ->
                listener.onDialogPositiveClick(this, binding.username.text.toString())
                dialog?.cancel()
            }
            .setNegativeButton("cancel"
            ) { dialog, id ->
                getDialog()?.cancel()
            }
        builder.create()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.