iT邦幫忙

2021 iThome 鐵人賽

DAY 10
0
Mobile Development

如何開發適合電子書閱讀器使用的瀏覽器 Android APP系列 第 10

電子書閱讀器上的瀏覽器 [Day10] 支援畫面點擊翻頁

既然是電子書閱讀器,一般人最常拿來用的功能應該就是看電子書吧。看電子書時如果要翻頁的話,通常會點擊畫面的兩側。那瀏覽器是不是也可以讓它有一樣的行為呢?這麼一來既可以一頁一頁地翻看網頁,而且又不用點擊那小小的按鈕或是按那可能不存在的音量鍵。

這一篇我們來看看怎麼在現有的介面上實作這功能。

新增點擊區域

Activity 畫面中,主體是 WebView,要讓它可以點擊翻頁的話,我們在 Layout 中要疊上兩塊透明的 View,用來接收使用者的行為。所以我們在裡頭新增了 touch_left 和 touch_right。

    <FrameLayout android:id="@+id/main_content"
         android:layout_width="match_parent"
         android:layout_height="match_parent"/>
         android:layout_height="match_parent">
     </FrameLayout>
     <View android:id="@+id/touch_left"
         android:layout_width="80dp"
         android:layout_height="match_parent"
         android:visibility="invisible"
         android:background="@color/color_transparent"
         android:onClick="onClick"
         />
     <View android:id="@+id/touch_right"
         android:layout_alignParentRight="true"
         android:layout_width="80dp"
         android:layout_height="match_parent"
         android:visibility="invisible"
         android:background="@color/color_transparent"
         android:onClick="onClick"
         />

功能實作

然後在 BrowserActivity.kt 中將這兩個 View 串到翻頁的功能上。

R.id.omnibox_touch -> toggleTouchFeature()
R.id.touch_left -> ninjaWebView.pageUpWithNoAnimation()
R.id.touch_right -> ninjaWebView.pageDownWithNoAnimation()

至於上面的 R.id.omni_box_touch,則是工具列上頭新增的 ImageButton,用來開關點擊翻頁的功能。有的時候網頁中會有一些元件剛好在點擊翻頁的區域,這時就要暫時關掉這功能,才能正常操作網頁。

toggleTouchFeature() 的實作也很單純:在開啟的狀態下,會把兩個新增的 View 設為 Visible;關閉功能時,將它們設為 Invisible 就行了。(下面的 findViewById 應該要在畫面初始時,只做一次就好。這裡是錯誤示範 :p)

    private fun  toggleTouchFeature() {
         if (binding.omniboxTouch.alpha != 1.0F) {
             binding.omniboxTouch.alpha = 1.0F
             findViewById<View>(R.id.touch_left).visibility = VISIBLE
             findViewById<View>(R.id.touch_right).visibility = VISIBLE
         } else {
             binding.omniboxTouch.alpha = 0.5F
             findViewById<View>(R.id.touch_left).visibility = INVISIBLE
             findViewById<View>(R.id.touch_right).visibility = INVISIBLE
         }
     }

大家有沒有發現一件事,BrowserActivity.java 變成 BrowserActivity.kt 了。沒錯,為了開發上的方便,以及享有更簡潔的語法,我把這個最重要的 class 轉換成 Kotlin 了。雖然經歷了點 refactoring,不過改完整個檔案大小又精簡了不少。

下面就讓我們來看一下完成後的效果吧

Yes

參考原始碼版本

目前的實作,只是很簡單地用兩個 View 來接受 touch event。之後會有一回解釋怎麼為這兩個 View 畫上邊框,讓使用者在點擊時可以知道有效的範圍在哪;同時,還提供多種不同的位置,讓使用者可以依照自己的使用習慣來設。

下一篇,會進入比較技術一點的內容。我們要來看看怎麼支援類似 Safari, Chrome, Firefox 等大型瀏覽器中提供的 Reader Mode 功能,讓網頁可以用更簡潔的方式呈現出來,方便閱讀。


上一篇
電子書閱讀器上的瀏覽器 [Day09] 支援音量鍵翻頁
下一篇
電子書閱讀器上的瀏覽器 [Day11] 移植 Firefox 閱讀模式
系列文
如何開發適合電子書閱讀器使用的瀏覽器 Android APP30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言