7

我正在使用 Android Studio 3.0 RC2 和 Kotlin。

当我尝试访问 UI 组件时,除非我先写 findViewById,否则应用程序会崩溃。我以为 Kotlin 应该摆脱写findViewById线的麻烦?UI 是一个fragment,我正在尝试从相同的fragment代码访问。有没有办法不必写 findViewById?

这些行有效:

var userNameField = view?.findViewById<EditText>(R.id.userNameTextField) as EditText
userNameField.setText("hello world")

没有 findViewById 行,此行不起作用

userNameTextField.setText("hello world")

我什至有

import kotlinx.android.synthetic.main.fragment_sign_in.*

onCreateView()代码:

 override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {
    // Inflate the layout for this fragment
    var view = inflater!!.inflate(R.layout.fragment_sign_in, container, false)

    var userNameField = view?.findViewById<EditText>(R.id.userNameTextField) as EditText
    userNameField.setText("hello world")

    return view
}
4

5 回答 5

3

在 onCreateView 中只返回膨胀的视图。

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {
    // Inflate the layout for this fragment
return inflater!!.inflate(R.layout.fragment_sign_in, container, false)

}

在 onViewCreated 你可以访问你的视图组件

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        userNameField.setText("hello world")
    }
于 2017-10-23T19:44:08.653 回答
3

我是通过搜索同样的问题被带到这里的。我错过了将 kotlin-android-extensions 添加到 build.gradle:

apply plugin: 'kotlin-android-extensions'
于 2020-11-01T13:10:23.610 回答
2

无法访问像 OP 这样的 ui 组件,在应用程序 gradle 中需要如下所示:

plugins {
    ...
    id 'kotlin-android-extensions'
}

即使在添加此行之后,android studio 仍然无法自动解析 kotlin 合成的导入,因此您可能需要使缓存无效并重新启动。

如果仍然无法正常工作,则根据视图手动导入

  • 活动/片段视图:导入 kotlinx.android.synthetic.main.<your_activity_view>.*
  • 普通视图:import kotlinx.android.synthetic.main.<your_layout_view>.view.*
于 2020-11-25T08:16:31.390 回答
0

我遇到了类似的问题。

我有一个私人活动。我还导入了 kotlinx 库。但我无法从该函数访问 editText。

我刚刚删除了该功能并再次定义了它。

瞧!有效。

于 2018-12-10T15:07:14.793 回答
0

对于那些在 2021 年遇到此问题的人:

我知道过去有人问过这个问题,但由于它在这里仍然相关,我想帮助其他人:今天我遇到了这个问题并尝试了建议的方法,不幸的是,

plugins { ... id 'kotlin-android-extensions' }

不再工作或更准确地说已被弃用,所以尝试使用 Jetpack 视图绑定方法,你会很好。

添加 Gradle Kotlin Android 扩展依赖项后我收到的消息是:“kotlin-android-extensions”Gradle 插件已弃用。请使用此迁移指南(单击此处)开始使用视图绑定。(单击此处)和“kotlin-parcelize”插件。

于 2021-01-11T15:30:36.623 回答