Avatar ·

在Kotlin Fragment中访问View时出现NullPointerException:原因与解决方案

大家好!我是Kotlin和Android开发的新手。遇到了一个问题:在Fragment中尝试访问界面元素(TextView、Button)时,我得到了NullPointerException。这是我的代码: ```kotlin class MyFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_my, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // 这里尝试访问view val textView = view.findViewById(R.id.my_text_view) textView.text = "你好" // NPE! } } ``` 但有时我使用kotlin-android-extensions并这样写: ```kotlin import kotlinx.android.synthetic.main.fragment_my.* class MyFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedI