はじめに
業務でPIP(ピクチャーインピクチャー)を実装しそうな予定があるので予習も兼ねて超簡単に実装してみる。
こんなやつ

早速実装
まずはManifest.xmlに記述。
Manifest.xml
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:supportsPictureInPicture="true">
適当なFragmentにピクチャーインピクチャーを開始するボタンを設置。
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.home.HomeFragment">
<com.google.android.material.button.MaterialButton
android:id="@+id/start_pip_btn"
android:layout_width="100dp"
android:layout_height="100dp"
android:text="@string/start_pip_mode"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Fragmentにクリックリスナーを設置
HomeFragment.kt
@RequiresApi(Build.VERSION_CODES.O)
private fun setClick() {
binding.startPipBtn.setOnClickListener {
startPIPMode()
}
}
クリックされたタイミングでピクチャーインピクチャーを開始
HomeFragment.kt
@RequiresApi(Build.VERSION_CODES.O)
private fun startPIPMode() {
val builder = PictureInPictureParams.Builder()
// PIPモード中のサイズを指定
builder.setAspectRatio(Rational(16, 9))
this.activity?.enterPictureInPictureMode(builder.build())
}
気をつけること
ピクチャーインピクチャーはAPIレベル26(Android8)からしか使用できないみたいです。
最後に
思ったより簡単にピクチャーインピクチャーを実装できました。
ただ、アプリ内でピクチャーインピクチャーをやる方法がわからないのでわかる方は教えて頂けると幸いです。
サンプルコードはGitHubに載せてあります。
ではまたっ!