怠慢プログラマーの備忘録

怠慢でナマケモノなプログラマーの備忘録です。

【Kotlin】カメラ/アルバム機能[備忘録]

カメラ/アルバム機能をKotlinで実装した時の備忘録

Adapter

class PostBuzzRecyclerViewAdapter(private val context: Context,
                                  private val activity: PostBuzzActivity)
    :  RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    companion object {
        const val CAMERA_REQUEST_CODE = 1
        const val CAMERA_PERMISSION_REQUEST_CODE = 2
        const val RESULT_PICK_IMAGEFILE = 1000
        const val REQUEST_GALLERY = 0
    }

    private var cameraHolder: PostBuzzCameraRecyclerHolder? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val layoutInflater = LayoutInflater.from(context)
        return this.createPostBuzzCameraRecyclerHolder(parent, layoutInflater)
    }

    override fun getItemCount(): Int {
        return 1
    }

    override fun getItemViewType(position: Int): Int {
        return position
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    }

    private fun createPostBuzzCameraRecyclerHolder(parent: ViewGroup,
                                                 layoutInflater: LayoutInflater): RecyclerView.ViewHolder {
        val mView = layoutInflater.inflate(R.layout.post_buzz_camera_recycler_item, parent, false)
        val holder = PostBuzzCameraRecyclerHolder(mView)
        this.cameraHolder = holder
        holder.cameraImageButton.setOnClickListener {
            val items = arrayOf("カメラ", "アルバム")
            AlertDialog.Builder(this.activity)
                    .setTitle("選択してください")
                    .setItems(items, DialogInterface.OnClickListener { dialog, which ->
                        when (which) {
                            // Camera
                            0 -> {
                                Intent(MediaStore.ACTION_IMAGE_CAPTURE).resolveActivity(this.context.packageManager)?.let {
                                    if (checkCameraPermission()) {
                                        this.takePicture()
                                    } else {
                                        grantCameraPermission()
                                    }
                                } ?: Toast.makeText(this.context, "カメラを扱うアプリがありません", Toast.LENGTH_LONG).show()
                            }
                            1 -> {
                                this.selectGallery()
                            }
                        }
                    })
                    .show()
        }
        return holder
    }

    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        data?.extras?.get("data")?.let { mdata ->
            this.cameraHolder?.let {
                it.cameraImageView.setImageBitmap(mdata as Bitmap)
            }
        } ?: run {
            // アルバムの画像が選択された場合
            if (resultCode != 0) {
                val uri = data?.getData()
                val inputStream = this.activity.contentResolver?.openInputStream(uri)
                val img: Bitmap? = BitmapFactory.decodeStream(inputStream)
                this.cameraHolder?.let {
                    it.cameraImageView.setImageBitmap(img)
                }
            }
        }
    }

    private fun checkCameraPermission() = PackageManager.PERMISSION_GRANTED ==
            ContextCompat.checkSelfPermission(this.context, android.Manifest.permission.CAMERA)


    private fun takePicture() {
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE).apply {
            addCategory(Intent.CATEGORY_DEFAULT)
        }

        this.activity.startActivityForResult(intent, CAMERA_REQUEST_CODE)
    }

    private fun selectGallery(){
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.type = "image/*"
        this.activity.startActivityForResult(intent, RESULT_PICK_IMAGEFILE)
    }

    private fun grantCameraPermission() =
            ActivityCompat.requestPermissions(this.activity,
                    arrayOf(android.Manifest.permission.CAMERA),
                    CAMERA_PERMISSION_REQUEST_CODE)
}

Activity

class PostBuzzActivity : AppCompatActivity() {
    private var adapter: PostBuzzRecyclerViewAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_post_buzz)
        this.createRecyclerView()
    }

    // 画像が選択された後にくる
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        this.adapter?.let {
            it.onActivityResult(requestCode, resultCode, data)
        }
    }

    private fun createRecyclerView() {
        val recyclerView = findViewById(R.id.PostBuzzRecyclerViewID) as RecyclerView
        this.adapter = PostBuzzRecyclerViewAdapter(this, this)
        recyclerView.adapter = this.adapter
        recyclerView.layoutManager = LinearLayoutManager(this)
    }
}

Kotlinスタートブック -新しいAndroidプログラミング

Kotlinスタートブック -新しいAndroidプログラミング