【Android】如何在Webview嵌入Youtube影片?
想要在自己的App內嵌入Youtube影片,
而且不會跳轉到Youtube App中去播放,
要如何實現呢?
首先,要先拿到Youtube影片的嵌入網址,
點選Youtube影片下方的分享按鈕

點擊嵌入選項

此時會看到一連串的嵌入影片的網址,點擊複製並且放到Code裡面即可

若是想要自動播放,需要在影片ID後面加入 "?&autoplay=1"
https://www.youtube.com/embed/th9WMMJuOFU?&autoplay=1\
這樣預先動作就準備好囉~
接下來是程式碼的部分
加入WebVIew物件

載入影片預覽圖片

設定WebVIew
setJavaScriptEnabled(true) // 需要設定可以使用JavaScript setUserAgentString(USERAGENT) // 若是需要自動播放影片,UserAgent一定要設定 setWebViewClient(new WebViewClient()); // 嵌入網址需使用WebViewClient()去Request
設定網址並播放
loadUrl(VideoEmbededAdress); //設定非嵌入網址給WebView,此範例為嵌入影片,所以loadUrl不適用 loadDataWithBaseURL("", VideoEmbededAdress, mimeType, encoding, ""); //設定嵌入影片網址
Request 播放,會得到Request的URL,可以在此Debug使用

經過以上的步驟,就完成囉
來欣賞Demo作品吧~
有任何問題都歡迎留言討論喔~