Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i create a function outside of the MainActivity Kotlin

I have a function :

fun showDialogWindow(){
val builder = AlertDialog.Builder(this)
val inflater = layoutInflater
val dialogLayout = inflater.inflate(R.layout.dialog_window, null)
val editText = dialogLayout.findViewById<EditText>(R.id.change_balance_edittext)

with(builder) {
    setPositiveButton("Ok"){dialog, which ->
        Values.balance = editText.text.toString().toFloat()
    }
    setNegativeButton("Cancel"){dialog, which ->
    }
    setView(dialogLayout)
    show()
}
}

I want to create it in separate file, when i try to do it, i have some mistakes: in 2 line ‘this’ is not defined in this context,in 3 Unresolved reference: layoutInflater and in 13 Overload resolution ambiguity. In MainActivity fun is working. How can i solve it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First I would try to look at how the language works and where you can call variables.

Per example, the "this" error is because when you are calling "this" in the MainActivity, it gets the activity type, probably "AppCompatActivity". When calling in a new file, you need to pass the value "this" as a parameter in the funtion.

fun showDialogWindow(mainActivity : Context){
val builder = AlertDialog.Builder(mainActivity )
val inflater = layoutInflater
val dialogLayout = inflater.inflate(R.layout.dialog_window, null)
val editText = dialogLayout.findViewById<EditText>(R.id.change_balance_edittext)

    with(builder) {
        setPositiveButton("Ok"){dialog, which ->
            Values.balance = editText.text.toString().toFloat()
    }
    setNegativeButton("Cancel"){dialog, which ->
    }
    setView(dialogLayout)
    show()
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading