How can i call a function when the user touch Pop Back (Back Button on Bottom Navigation) (Right Bottom button on the phone) - kotlin

I want to call a function when the user touches Back on the Bottom Navigation? Is there any method or a way for this?

Old
You can override onBackPressed method in your activity class.
Recent (API >= 33)
But onBackPressed is deprecated after API 33.
Now you can add callback on onBackPressedDispatcher instead to override onBackPressed
class MyActivity : AppCompatActivity() {
private val callback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
// something you want to do
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ...
this.onBackPressedDispatcher.addCallback(this, callback)
}
This code is for Activity. If you want to set back button action in Fragment, you can check this document.
https://developer.android.com/reference/androidx/activity/OnBackPressedDispatcher

Use override fun onBackPressed() method
override fun onBackPressed(){
// Do something
// add super.onBackPressed() if you want to call the normal back function
}
May this solution help you.
Thank you

Related

Weird function behaviour inside composable function

Whenever I tell my NavGraph to start on this composable screen:
#Composable
fun LiveTrainingScreen(viewModel: LiveTrainingViewModel = viewModel(), navController: NavController) {
viewModel.context = LocalContext.current
viewModel.scope = rememberCoroutineScope()
viewModel.navController = navController
val largeVideoPlayerHandler = viewModel.InitLargeVideoDisplay(CameraLink.cockPitRight) //exoplayer saved within this handler and refrences is made within the viewModel
val smallVideoPlayerHandler = viewModel.InitSmallVideoDisplay(CameraLink.navigationAndAltitudeDisplay) //exoplayer saved within this handler and refrences is made within the viewModel
//lots of code
}
and when I want to switch the mediaType/video that is being displayed of the Exoplayer this function will work:
class LiveTrainingViewModel(application: Application) : AndroidViewModel(application) {
fun SwitchLargeVideoDisplay(cameraLinkObject: CameraLinkObject) {
UpdateLargeVideoDisplayCameraLinkObject(cameraLinkObject)
largeVideoDisplay.videoPlayer.setMediaItem(MediaItem.fromUri(cameraLinkObject.url))
largeVideoDisplay.videoPlayer.prepare()
}
}
But whenever I load this Screen from another screen this large screen update function won't work for some reason?
Does anybody know why?

How to access the switch element of Mainactivity in a class that inherits NotificationListenerService in Kotlin

In NotificationListener, I want to implement code to perform different functions according to the state value of the switch element in activity_main.xml.
So inside the onNotificationPosted() function
I need to know the state of the switch through the following code.
val volumeSeekBar:Switch = findViewById(R.id.switch_id)
To do this, I wrote the following code, and it turns off as soon as the app is launched.
How to access the switch element of Mainactivity in a class that inherits NotificationListenerService ??
NotificationListener.kt
class NotificationListener(activity:MainActivity) : NotificationListenerService() {
override fun onCreate() {
...
}
override fun onListenerConnected() {
...
}
override fun onNotificationPosted(sbn: StatusBarNotification) {
val volumeSeekBar:Switch = activity.findViewById(R.id.switch_id) <-- doesn't work
}
}

SavedState module Android Kotlin with View Model - value does not seem to save

I have followed the instructions in Google Codelab about the Saved state module.
My gradle dependency is:
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-rc03"
My View Model factory is:
class MyViewModelFactory(val repository: AppRepository, owner: SavedStateRegistryOwner,
defaultArgs: Bundle? = null) : AbstractSavedStateViewModelFactory(owner, defaultArgs) {
override fun <T : ViewModel?> create(
key: String,
modelClass: Class<T>,
handle: SavedStateHandle): T {
return MyViewModel(repository, handle) as T
}
}
My View model:
class MyViewModel constructor(val repository: AppRepository, private val savedStateHandle: SavedStateHandle): ViewModel() {
fun getMyParameter(): LiveData<Int?> {
return savedStateHandle.getLiveData(MY_FIELD)
}
fun setMyParameter(val: Int) {
savedStateHandle.set(MY_FIELD, val)
}
}
My Fragment:
class MyFragment : androidx.fragment.app.Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
arguments?.let {
var myField = it.getInt(MY_FIELD)
activitiesViewModel.setMySavedValue(myField ?: 0)
}
}
}
When the app is being used, the live data for the saved state field updates correctly. But as soon as I put the app in background (and I set "don't keep activities" in developer options), and then re open app, the live data shows a value as if it was never set. In other words, the saved state handle seems to forget the field I am trying to save.
Any thoughts?
I had the same problem. It was solved by the fact that I stopped requesting saved values from SavedStateHandle in the onRestoreInstanceState method. This call is correctly used in the onCreate method.

What's callback in Kotlin?

I'm learning kotlin in intelij Idea, and I have to make presentation about interfaces. One subject is callback, where can I find information about it? or can you tell me simply, veery simply, what's call back?
fun main() {
val myphone = Myphone()
myphone.phoneOn()
myphone.onClick()
myphone.onTouch()
myphone.openApp()
myphone.closeApp()
}
interface Application {
var AppName: String
fun openApp()
fun closeApp() {
println("$AppName App is closed!")
}
}
interface Button {
var helloMessage: String
fun phoneOn()
fun onClick()
fun onTouch() {
println("The screen was touched!")
}
}
class Myphone: Button, Application {
override var AppName: String = "Facebook"
override fun openApp() {
println("$AppName Is Open!")
}
override var helloMessage: String = "Hello"
override fun onClick() {
println("The screen was clicked!")
}
override fun phoneOn() {
println("$helloMessage !")
}
}
VERY simply: callback means the function, that is executed on the other function's finish or some specific event happening.
fun execute() {
// Some logic
executeAnotherOnFinish();
}
OR
// filter executes only after array converted to list
myIntArray.toList().filter { it > 0 }
OR
myListener.notify()
// Listener class methid
notify() {
// Do some work
executeCallback()
}
Callback is not just Kotlin related, its very common programming technique which is primarily used with asynchronous programming. The simplest explanation is that it is function that will be called back (hence the name) once some asynchronous event has occurred.
Button's onClick function is quite good example of that, we have some logic that we need to execute but we want it to run only when button is clicked so we provide callback which will be called once that button is clicked.

How can I perform clean up actions upon closing a view in Kotlin/TornadoFX?

I have been searching the docs and IDE autocomplete suggestions and cannot figure this out. The closest I have found is onDelete(), and it is not working the way I envision.
I just need a way to run some clean up code when a view is closed.
Here is a failed attempt using the simple example from the docs.
import tornadofx.*
class MyApp: App(MyView::class)
class MyView: View() {
// this does not print when the window is closed
override fun onDelete() {
super.onDelete()
println("Print on close!")
}
override val root = vbox {
button("Press me")
label("Waiting")
}
}
fun main(args: Array<String>) {
launch<MyApp>(args)
}
Another failed attempt per a suggestion below:
import tornadofx.*
class MyApp: App(MyView::class)
class MyView: View() {
// "Closing" is never printed when closing this view"
override fun onDock() {
currentWindow?.onHidingProperty()?.onChangeOnce {
println("Closing")
}
}
override val root = vbox {
button("Press me")
label("Waiting")
}
}
fun main(args: Array<String>) {
launch<MyApp>(args)
}
I'm using this in my project right now. setOnCloseRequest is my go to!
override fun onDock() {
currentWindow?.setOnCloseRequest {
println("Closing")
}
}
onDelete is a callback for the Workspace in TornadoFX, and will be called if you click the Delete button in the Workspace when that View is active. What you can do is override onDock and add a once change listener to the hiding property:
override fun onDock() {
currentWindow?.onHidingProperty()?.onChangeOnce {
println("Closing")
}
}
If you're looking for cleanup code when closing the application, another option that works for child views/fragments/controllers is an FXEvent that's fired on close. The event is defined like this:
object ApplicationClosingEvent : FXEvent()
In the main App, I override stop() so that the event is fired:
override fun stop() {
fire(ApplicationClosingEvent)
}
Since stop() is running on the application thread, the event is fired and handled synchronously. Finally, in each view/fragment/controller you can subscribe like so:
subscribe<ApplicationClosingEvent> {
// Clean-up code goes here
}
The primary benefit of using an event instead of a window callback is that you can have many different views subscribing to it, rather than a single window callback.