电子书阅读器上的浏览器 [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,不过改完整个档案大小又精简了不少。

下面就让我们来看一下完成後的效果吧

参考原始码版本

目前的实作,只是很简单地用两个 View 来接受 touch event。之後会有一回解释怎麽为这两个 View 画上边框,让使用者在点击时可以知道有效的范围在哪;同时,还提供多种不同的位置,让使用者可以依照自己的使用习惯来设。

下一篇,会进入比较技术一点的内容。我们要来看看怎麽支援类似 Safari, Chrome, Firefox 等大型浏览器中提供的 Reader Mode 功能,让网页可以用更简洁的方式呈现出来,方便阅读。


<<:  OpenStack Neutron 介绍 1

>>:  [Day10] 文本/词表示方式(一)-前言

Day10-JDK查看虚拟机配置讯息工具:jinfo

jinfo介绍 jinfo全名:Configuration Info for Java,生成虚拟机配...

轻松救回被删语音备忘录

如何救回 iPhone 13/12 Pro/12/11/11 Pro/XS/XR/X 被删除的录音档...

予焦啦!使用 GDB 推进

本节是以 Golang 上游 ee91bb83198f61aa8f26c3100ca7558d30...

[Day16] Functions

Cloud Function 是一款 Serverless 的服务,使用者不需要管理服务器。Goog...

JavaScript变数

变数(Variable)在JavaScript语言中扮演了重要的资料存放角色。JavaScript变...