Home > Blockchain >  How can i create a function outside of the MainActivity Kotlin
How can i create a function outside of the MainActivity Kotlin

Time:12-17

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?

CodePudding user response:

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