一、需求分析
需要实现页面内文字搜索关键词功能,将匹配到的关键词高亮显示,且能够点击按钮切换到下一个关键词所在位置。首先需要高亮匹配到所有的关键词,这个可以使用字符串的replaceAll实现,切换到关键词的位置,需要滑动页面,那可能会想到ScrollView和TextView来实现,但是textview不是两端对齐的,获取位置会有偏差。于是想到利用webview来实现。
二、功能实现
1.资源文件
代码如下:
<EditText
android:id="@+id/am_et_search"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="5dp"
android:background="@null"
android:hint="请输入关键字"
android:textColor="@color/black"
android:textSize="16sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<Button
android:id="@+id/am_btn_search"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:text="搜 索"
android:textSize="16sp"
android:textColor="@color/white"
android:layout_margin="5dp"
/>
<Button
android:id="@+id/am_btn_next"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="下一个"
android:textSize="16sp"
android:textColor="@color/white"
android:layout_margin="5dp"
/>
<Button
android:id="@+id/am_btn_forward"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="上一个"
android:textSize="16sp"
android:textColor="@color/white"
android:layout_margin="5dp"
/>
</LinearLayout>
<android.webkit.WebView
android:id="@+id/am_webview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:paddingBottom="10dp" />
2.核心代码
webview的findAllAsync可以实现高亮显示匹配到的关键词,webview的findNext()方法接收一个布尔值参数,true为查找下一个,false为查找上一个。另外如果想要根据当前匹配关键词的位置做一些事情,可以调用webview的find相关的监听事件来实现。
代码如下:
webView = findViewById(R.id.am_webview);
editText = findViewById(R.id.am_et_search);
btnSearch = findViewById(R.id.am_btn_search);
btnNext = findViewById(R.id.am_btn_next);
btnForword = findViewById(R.id.am_btn_forward);
webView.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);
btnSearch.setOnClickListener(view -> webView.findAllAsync(editText.getText().toString()));
btnNext.setOnClickListener(view -> webView.findNext(true));//查找下一个
btnForword.setOnClickListener(view -> webView.findNext(false));//查找上一个
2.效果图
![](https://img-blog.csdnimg.cn/39e3cb2dcafb48a9ac5c578ad40345f2.png)