【发布时间】:2017-10-23 05:21:57
【问题描述】:
我正在使用 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
}
【问题讨论】:
-
因为它不知道
userNameField是EditText。 -
显示你的
onCreate方法 -
您使用的是哪个 kotlin 版本?
-
检查github.com/gradle/kotlin-dsl/issues/377。它可能对您有所帮助。
-
视图名为
userNameTextField,但您使用的是userNameField。
标签: android kotlin android-studio-3.0 kotlin-extension