코딩하는 일용직 노동자

유튜브를 웹뷰로 구성하기 (1) 본문

안드로이드

유튜브를 웹뷰로 구성하기 (1)

bacass 2020. 5. 11. 15:06

유튜브에서 url을 공유할때 보면  www.youtu.be/nA8PosPb70c 이런식으로 url 이 클립보드에 복사됩니다.
이걸 웹뷰에서 열면 영상 뿐만 아니라 좋아요 버튼같은 유튜브의 다른 불필요한 UI도 화면에 표시됩니다.

웹뷰에 유튜브 영상 알맹이만 꽉차게 표시하고 싶으면
웹뷰에  www.youtube.com/embed/영상아이디 이렇게 하면 됩니다.

영상아이디는 유튜브 공유 URL 의 가장 마지막 / 뒤에 영문+숫자가 아이디입니다.
www.youtube.com/embed/nA8PosPb70c
이렇게 호출시키니깐 웹뷰 화면에 영상이 꽉 차게 표시 됩니다. ^^

wvYoutube.settings.apply {
    javaScriptEnabled = true
    setAppCacheEnabled(true)
    pluginState = WebSettings.PluginState.ON
    useWideViewPort = true
    loadWithOverviewMode = true
}
wvYoutube.webChromeClient = VideoEnabledWebChromeClient()
wvYoutube.webViewClient = HelloWebViewClient()
wvYoutube.loadUrl("https://www.youtube.com/embed/$movieId")



class CustomWeb: WebChromeClient() {
    var videoCustomView: View? = null
    var customView : FrameLayout? = null

    override fun onShowCustomView(view: View?, callback: CustomViewCallback?) {
        if (videoCustomView != null) {
            callback?.onCustomViewHidden()
            return
        }

        val frame: FrameLayout = view as FrameLayout
        val v1: View = frame.getChildAt(0)

        view.setLayoutParams(FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT, Gravity.CENTER))
        v1.setOnKeyListener(object : View.OnKeyListener {
            override fun onKey(v: View?, keyCode: Int, event: KeyEvent?): Boolean {
                if (keyCode == KeyEvent.KEYCODE_BACK && event?.action == KeyEvent.ACTION_DOWN) {
                    onHideCustomView()
                    return true
                }
                return false
            }
        })

        videoCustomView = view
        customView?.visibility = View.VISIBLE
        customView?.setBackgroundColor(Color.BLACK)
        customView?.bringToFront()

        customView?.addView(videoCustomView)
    }

    override fun onHideCustomView() {
        super.onHideCustomView()

        customView?.removeView(videoCustomView)
        videoCustomView = null
        customView?.visibility = View.INVISIBLE
    }
}

internal inner class HelloWebViewClient : WebViewClient() {
    override fun shouldOverrideUrlLoading(webview: WebView, url: String): Boolean {
        webview.webChromeClient = CustomWeb()
        webview.loadUrl(url)

        return true
    }
}

 

웹뷰에 유튜브 영상뿐만 아니라 좋아요, 싫어요 버튼 UI 가 다 표시된다.

 

두번째 사진엔 영상 알맹이만 딱 표시된다