使用findViewById开发登录页时遇参数ID未传值错误求助
问题:登录页面提示“参数‘ID’未传入对应值”
错误原因及修复方案
1. findViewById泛型参数写法错误
你的Kotlin代码中,findViewById的泛型参数误用了字符串(如<"username">),正确写法是指定控件的实际类型(比如EditText、Button)。
错误代码:
val username = findViewById<"username">(R.id.username) val password = findViewById<"password">(R.id.password) val loginButton = findViewById<"login_button">(R.id.login_button)
修正后代码:
val username = findViewById<EditText>(R.id.username) val password = findViewById<EditText>(R.id.password) val loginButton = findViewById<Button>(R.id.login_button)
2. XML中hint属性引用错误
XML里的android:hint="@+string/Username"写法错误,@+用于创建新资源ID,引用已有字符串资源应使用@string/xxx(需确保res/values/strings.xml中已定义对应字符串,比如<string name="username">用户名</string>)。
错误代码片段:
android:hint="@+string/Username" android:hint="@+string/Password"
修正后代码片段:
android:hint="@string/username" android:hint="@string/password"
3. Button点击事件重复绑定
XML中的Button同时设置了android:onClick="handleLoginClick"和代码中的setOnClickListener,会导致逻辑冲突。建议移除其中一种绑定方式,比如删除XML中的android:onClick属性。
修正后的Button XML代码:
<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" />
完整修正后的代码
LoginActivity.kt
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) val username = findViewById<EditText>(R.id.username) val password = findViewById<EditText>(R.id.password) val loginButton = findViewById<Button>(R.id.login_button) loginButton.setOnClickListener { val inputUsername = username.text.toString() val inputPassword = password.text.toString() if (inputUsername == "lukejjones" && inputPassword == "test123") { Toast.makeText(this, "Access Granted", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this, "Access Denied!", Toast.LENGTH_SHORT).show() } } }
注:内部变量名改为inputUsername和inputPassword,避免与外部控件变量重名,提升代码可读性。
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" />
内容的提问来源于stack exchange,提问作者Luke Jones
相关产品推荐
相关产品推荐

