Issue
This is my very first time using Kotlin/Android App Development, so I apologise if I am missing something simple. I have a background in Java and C#.
I'm trying to display an AlertBox containing X information. All the tutorials I am reading/watching stay that the constructor should be:
val builder = AlertDialog.Builder(this)
This issue I am having trouble with is the "this" part. I get a Type Mismatch error for the "this" reference.
I have tried searching for a solution and I find variations of the same:
Instead of passing "this" pass the Context of Calling Activity or Application.
something like,
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
The problem is: I don't understand what I am supposed to enter. I have tried writing "mContext" (I didn't expect this to work) "Employee" (The name of the class) and "MainActivity", but none of these seem to work.
The structure of my code is something like:
class MainActivity : AppCompactActivity() {
class Employee() {
companion object {
}
fun main(args: Array<String>) {
val alertDialogBuilder = AlertDialog.Builder(this)
}
}
}
Thanks for taking the time to look over this and help out.
Solution
In order to access this
from an inner class in Kotlin you have to mark it as inner
(so it can access parent class members) and use this@ParentClass
(to disambiguate between this
that refers to the Employee
class instance), like this:
class MainActivity : AppCompatActivity() {
inner class Employee {
fun main(args: Array<String>) {
val alertDialogBuilder = AlertDialog.Builder(this@MainActivity)
}
}
}
Alternately, you can have the class method (or constructor) take a context as an argument (without making it inner
)
class MainActivity : AppCompatActivity() {
class Employee {
fun main(context: Context, args: Array<String>) {
val alertDialogBuilder = AlertDialog.Builder(context)
}
}
}
Answered By - Tyler V
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.