Search code examples
androidandroid-activity

Press a button to execute an operation instead of using back button


I am selecting an image from gallery.

press back button

When I press the back button, the getResultCamera.launch(intent) is called and an operation takes place.

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_selected_image)

        image = findViewById(R.id.the_selected_image);
        srButton = findViewById(R.id.super_resolution_button)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
                val permissions = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
                requestPermissions(permissions, PERMISSION_CODE)
            } else {
                chooseImageGallery()
            }
        } else {
            chooseImageGallery()
        }


    }


private fun chooseImageGallery() {
        val intent = Intent(Intent.ACTION_PICK)
        intent.type = "image/*"
        getResultCamera.launch(intent)
    }


 private val getResultCamera =
        registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) {
            if (it.resultCode == Activity.RESULT_OK) {
                imageUri = it.data?.data as Uri
                image.setImageURI(imageUri)
                intent.putExtra("imageuri", imageUri)
                

            }
        }

So, it goes to the MainActivity, it loads the image and the operation takes place there.

Now, I want to use a button for the user to press instead of the back button.

So, I am trying something like:

private val getResultCamera =
        registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) {
            if (it.resultCode == Activity.RESULT_OK) {
                imageUri = it.data?.data as Uri
                image.setImageURI(imageUri)
                
                srButton.setOnClickListener { view: View ->
                    intent.putExtra("imageuri", imageUri)
                    val intent = Intent(this, MainActivity::class.java)
                    startActivity(intent)
                }

            }
        }

with button

but when I press the button, it just returns to the MainActivity without executing the operation.


Solution

  • Try putting finish() in the button's OnClickListener. This basically acts as though the user pressed the back button.