提问人:Luke Jones 提问时间:5/24/2023 更新时间:5/25/2023 访问量:35
findViewById 给我一个溃疡
findViewById is giving me an ulcer
问:
我正在尝试创建一个登录页面,但我得到的错误消息是没有为参数“ID”传递任何值,这意味着什么。
下面是 LoginActivity.kt 的代码:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
val username = findViewById<"username">(R.id.username)
val password = findViewById<"password">(R.id.password)
val loginButton = findViewById<"login_button">(R.id.login_button)
loginButton.setOnClickListener {
val username = username.text.toString()
val password = password.text.toString()
if (username == "lukejjones" && password == "test123") {
Toast.makeText(this, "Access Granted", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Access Denied!", Toast.LENGTH_SHORT).show()
}
}
以下是与此相关的activity_login.xml代码:
EditText
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="textPersonName"
android:padding="20dp"
android:hint="@+string/Username" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword"
android:padding="20dp"
android:hint="@+string/Password" />
<Button
android:id="@+id/login_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:background="@color/black"
android:text="Login"
android:textColor="@color/white"
android:onClick="handleLoginClick"
/>
答:
1赞
Tenfour04
5/25/2023
#1
尖括号之间的内容是您请求它查找的视图类型。它必须是 View 的具体类(或超类)。例如:
val username = findViewById<EditText>(R.id.username)
或者,你可以这样写:
val username: EditText = findViewById(R.id.username)
我建议您阅读 Java 文档的这两页,因为您需要对泛型有基本的了解才能在 Kotlin 中执行任何操作。由于某种原因,Kotlin 文档没有涵盖这一点:
- 为什么要使用泛型?但是对于这个,请注意,他们没有泛型的示例(他们必须强制转换)在 Kotlin 中是不存在的,因为 Kotlin 强制执行泛型(没有原始类型)。但它仍然说明了为什么首先使用泛型。
- 泛型类型
除了这两页之外,它开始更多地涉及特定于 Java 的内容,所以也许现在不要因为阅读这些内容而感到困惑。当您对这个概念更熟悉时,请阅读有关泛型和方差的 Kotlin 文档。
评论
<"username">
<"password">
<"login_button">
<EditText>
<Button>