I am selecting an image from gallery.
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)
}
}
}
but when I press the button, it just returns to the MainActivity
without executing the operation.
CodePudding user response:
Try putting finish()
in the button's OnClickListener. This basically acts as though the user pressed the back button.
CodePudding user response:
Please try this way may help you
private val pickImages = registerForActivityResult(ActivityResultContracts.GetContent()){ uri: Uri? ->
uri?.let { it ->
// The image was saved into the given Uri -> do something with it
imageUri = it
}
}
pickImages.launch("image/*")
srButton.setOnClickListener { view: View ->
intent.putExtra("imageuri", imageUri)
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
@Override
protected void onBackPressed(){
//Do not call super.onbackpressed here
}