我是Kotlin的新手,我试图在Kotlin中创建一个已开发的应用程序以用于学习,但遇到了错误。下面是代码;
class LoginActivity : AppCompatActivity() {
private var usernameET: EditText? = null
private var passwordET: EditText? = null
private var usernameTIL: TextInputLayout? = null
private var passwordTIL: TextInputLayout? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.login_layout);
usernameET = findViewById(R.id.et_username)
passwordET = findViewById(R.id.et_password)
usernameTIL = findViewById(R.id.til_username)
passwordTIL = findViewById(R.id.til_password)
usernameET.addTextChangedListener(MyTextWatcher(usernameET))
passwordET.addTextChangedListener(MyTextWatcher(passwordET))
btn_login.setOnClickListener { view ->
}
}
fun isUsernameValid(username: String): Boolean {
if (username.isEmpty()) {
this.usernameTIL.error = getString(R.string.username_error_msg);
requestFocus(usernameET);
return false;
} else {
this.usernameTIL.isErrorEnabled = false;
}
return true;
}
private fun isPasswordValid(password: String): Boolean {
if (password.isEmpty()) {
passwordTIL.error = getString(R.string.password_error_msg)
requestFocus(passwordET)
return false
} else {
passwordTIL.setErrorEnabled(false)
}
return true
}
fun requestFocus(view: View) {
if (view.requestFocus()) {
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
}
}
inner class MyTextWatcher(view: View) : TextWatcher {
private var mView: View = view
override fun afterTextChanged(p0: Editable?) {
when (mView.id) {
R.id.et_username -> {
isUsernameValid(usernameET.text.toString().trim())
}
R.id.et_password -> {
isPasswordValid(passwordET.text.toString().trim());
}
}
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
}
}
获取错误“将智能类型转换为“ EditText!”这是不可能的,因为'usernameET'是一个可变属性,这一次可能已经更改了”
usernameET.addTextChangedListener(MyTextWatcher(usernameET) )
passwordET.addTextChangedListener(MyTextWatcher(passwordET) )