【问题标题】:kotlinx.android.synthetic returns null in DialogFragmentkotlinx.android.synthetic 在 DialogFragment 中返回 null
【发布时间】:2021-02-22 18:55:11
【问题描述】:

在开始之前,我已经阅读了类似 this one 这样措辞相似的帖子,但它们对我不起作用。

正如我在标题中解释的那样,当我单击肯定按钮(在本例中为“确定”)时,我得到一个 NPE。如果有人能指出我做错了什么,那就太好了!以下是我的设置的抽象版本

MainFragment.kt

class MainFragment: DialogFragment() {

    override fun onCreateDialog(savedInstanceState: Bundle?) =
            AlertDialog.Builder(context!!)
                .setView(FragmentMainBinding.inflate(LayoutInflater.from(context)).root)
                .setTitle(R.string.title_main)
                .setNegativeButton(R.string.cancel, null)
                .setPositiveButton(R.string.ok) { _, _ -> onPositiveButtonTapped() }
                .create()

    private fun onPositiveButtonTapped() {
        val g = arrayListOf(ground_nbr_edit_text.text.toString()) // NullPointerException
        // ...
    }

}

fragment_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <EditText
            android:id="@+id/ground_nbr_edit_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>
</layout>

【问题讨论】:

    标签: android kotlin android-databinding


    【解决方案1】:

    DialogFragment 在onCreateDialog() 之后调用onCreateView(),然后将该视图用于对话框的内容,替换您已经在onCreateDialog() 中设置的任何内容。因此,将您的视图创建移至onCreateView()

    class MainFragment: DialogFragment() {
    
        override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?) =
            FragmentMainBinding.inflate(inflater).root
    
        override fun onCreateDialog(savedInstanceState: Bundle?) =
                AlertDialog.Builder(context!!)
                    .setTitle(R.string.title_main)
                    .setNegativeButton(R.string.cancel, null)
                    .setPositiveButton(R.string.ok) { _, _ -> onPositiveButtonTapped() }
                    .create()
    
        private fun onPositiveButtonTapped() {
            val g = arrayListOf(ground_nbr_edit_text.text.toString()) // NullPointerException
            // ...
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-30
      • 2016-11-07
      相关资源
      最近更新 更多