Search code examples
androidandroid-studiokotlinandroid-activity

How can I create a function in separate class and call it from MainActivity


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 Class, when i try to do it, i have some mistakes: in line 2 'this' is not defined in this context,in line 3 Unresolved reference: layoutInflater and in line 13 Overload resolution ambiguity. Within the MainActivity fun is working. How can i solve it?


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()
        }
    }