Advertisement
Guest User

simple code

a guest
Oct 4th, 2021
418
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.07 KB | None | 0 0
  1. class MainActivity : AppCompatActivity() {
  2.  
  3.     override fun onCreate(savedInstanceState: Bundle?) {
  4.         super.onCreate(savedInstanceState)
  5.         setContentView(R.layout.activity_main)
  6.  
  7.         val registerLauncher =
  8.             registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { ActivityResult ->
  9.                 if (ActivityResult.resultCode == Activity.RESULT_OK) {
  10.                     //當launcher 成功你所要執行的動作
  11.                     getIntentData(ActivityResult.data)
  12.                 }
  13.             }
  14.  
  15.         //點選Image View顯示file picker,選取讀片
  16.         findViewById<ImageView>(R.id.img).setOnClickListener {
  17.             Intent(Intent.ACTION_GET_CONTENT).also {
  18.                 it.type = "image/*"
  19.                 //底下是實際觸發launch
  20.                 registerLauncher.launch(it)
  21.             }
  22.         }
  23.      }
  24.  
  25.  
  26.     private fun getIntentData(data: Intent?) {
  27.         data?.data?.let {
  28.             curFile = it
  29.             findViewById<ImageView>(R.id.img).setImageURI(it)
  30.         }
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement