9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Androidで超簡単にPIP(ピクチャーインピクチャー)実装してみた

Last updated at Posted at 2023-03-07

はじめに

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

こんなやつ

pip_sample.gif

早速実装

まずは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に載せてあります。

ではまたっ!

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?