我正在使用以下代码从图库中选择图片。我想从此意图跟踪int值。
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
intent.putExtra("Position", 1)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE)
但是当我试图从onActivityResult中的意图中获取传递的值时,我只得到默认值[0]。
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
val selectedImageURI = data?.data
val position = data?.getIntExtra("Position", 0)
}
}
}
所以我的疑问是,是否可以通过意图选择器来跟踪值?如果是,怎么办?
答案 0 :(得分:1)
您必须在此行中使用requestCode
:
startActivityForResult(Intent.createChooser(intent, "Select Picture"), requestCode)
// for example use SELECT_PICTURE_POSITION_1 as requestCode
然后您将其恢复到此处:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK) {
when (requestCode) {// use your request code here
SELECT_PICTURE_POSITION_0 -> {
val selectedImageURI = data?.data
val position = data?.getIntExtra("Position", 0)
}
SELECT_PICTURE_POSITION_1 -> {
val selectedImageURI = data?.data
val position = data?.getIntExtra("Position", 1)
}
SELECT_PICTURE_POSITION_2 -> {
val selectedImageURI = data?.data
val position = data?.getIntExtra("Position", 2)
}
//other conditions here
}
}
}
使用多个请求代码来满足您的需求。
答案 1 :(得分:0)
是否可以通过意图选择器跟踪值?
不。您的问题与选择器无关。您将得到与startActivityForResult(intent), SELECT_PICTURE)
相同的结果。
startActivityForResult()
开始的活动没有要求将您碰巧放入该Intent
的任何其他物品退还给您。