shariful islam
shariful islam

Reputation: 399

Android, Kotlin : How to invoke MainActivity's method into sub class method in case of kotlin?

I am trying to invoke a MainActivity's method from a sub class. Look my code bellow.

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    open fun action(v: View){
        sub_class().test()
    }

    open fun toast(s: String){
        Toast.makeText(this, s, Toast.LENGTH_SHORT).show()
    }

    open class sub_class{
        open fun test(){
            val a = MainActivity()
            a.toast("test")
        }
    }
}

Here I want to invoke the toast() method into sub_class(). App crashed when I try to do that.

Note : Like this program work in Intellij Idea. I can't understand why this program don't work on app.

Upvotes: 0

Views: 110

Answers (1)

dzikovskyy
dzikovskyy

Reputation: 5087

Your sub_class is actually a Nested class. And you probably want to make it an Inner class. (Nested and Inner Classes)
Inner classes can access members of outer class as they carry a reference to an object of an outer class. So you don't need to create an instance of an outer class within an inner class.

In your case it will be like this:

open inner class sub_class{
        open fun test(){
            toast("test")
        }
    }

Upvotes: 2

Related Questions