Reputation: 187
I can't call function of my class from object inside this class. How should i do this ?
class LoginActivity: AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
}
private fun disableLoginButton(){
button_login.isEnabled = false
}
private object textChangeListener: TextWatcher{
override fun afterTextChanged(p0: Editable?) {
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
//Here i cannot call function
disableLoginButton() // unresolved reference.
}
}
}
But when i call LoginActivity().disableLoginButton()
instead disableLoginButton()
it's visible, but fails with
NullPointerException
on login_button
Upvotes: 0
Views: 93
Reputation: 1049
Try this :
class LoginActivity: AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
editTextSample.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable) {}
override fun beforeTextChanged(s: CharSequence, start: Int,
count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence, start: Int,
before: Int, count: Int) {
disableLoginButton()
}
})
}
}
private fun disableLoginButton(){
button_login.isEnabled = false
}
Upvotes: 2
Reputation: 634
EDIT: Doesn't work
In Java and Kotlin, "inner" means "capturing the outer instance", where as "nested" means simply declared inside something else. Java's static classes are only nested, non-static nested classes are inner. In Kotlin you have to explicitly declare something as "inner" (we reversed the Java's convention). So, your object is not inner, btu only nested. And no named object can be inner, in fact: named objects are singletons, so the can not depend on any kind of outer instance.
Try specifying the object as inner:
private inner object textChangeListener: TextWatcher{
override fun afterTextChanged(p0: Editable?) {
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int {
//Here i cannot call function
disableLoginButton() // unresolved reference.
}
}
This should allow you to access the outer scope.
Upvotes: 0