【Android】基于webView打造富文本编辑器(H5)

目录

  • 前言
  • 一、实现效果
  • 二、具体实现
    • 1. 导入网页资源
    • 2. 页面设计
    • 3. 功能调用
    • 4. 完整代码
  • 总结


前言

HTML5是构建Web内容的一种语言描述方式。HTML5是Web中核心语言HTML的规范,用户使用任何手段进行网页浏览时看到的内容原本都是HTML格式的,在浏览器中通过一些技术处理将其转换成为了可识别的信息。

而WebView 是一种嵌入式浏览器,原生APP应用可以用它来展示网络内容。其功能强大,除了具有一般View的属性和设置外,还可以对url请求、页面加载、渲染、页面交互进行强大的处理.。
在这里插入图片描述
所以,因为H5的跨平台和成本低的优势,越来越多的项目都使用了Android原生控件与WebView进行混合开发,用WebView加载html界面,实现本地安卓代码与HTML+CSS+JS的交互。

webView的基本使用可以参考这篇文章:https://blog.csdn.net/carson_ho/article/details/52693322

本文将利用webView实现一个富文本编辑器,它是一种可内嵌于浏览器,所见即所得的文本编辑器,其实质就是html代码,可改变文本样式、文间插入图片或视频等。我为了实现这一功能借鉴很多项目(主要是MRichEditor和RichEditTextCopyToutiao,都是基于 richeditor-android),修复了一些Bug,最终效果还行。借鉴的第三方库可移步我之前写的文章:常用的第三方开源库汇总


一、实现效果

在这里插入图片描述

在这里插入图片描述

二、具体实现

富文本编辑器主要功能就是文字大小、颜色、加粗、斜体、下划线、删除线、缩进、居中或靠左靠右,无序或有序列表,插入链接、图片、视频等。原有项目会存在一些导入html标签和输入框光标的bug,解决这些需要一点HTML+CSS+JS的知识。

1. 导入网页资源

在项目根目录下新建assets文件夹
在这里插入图片描述
导入资源:对于熟悉网页端的开发人员来说,修改这些并不难。
在这里插入图片描述

2. 页面设计

编辑器的一个按钮即对应着js中的一个函数,通过RichEditor自定义 view去调用js函数, 它继承自 Webview ,加载html文件,枚举类型Type定义了支持的排版格式。

public class RichEditor extends WebView {private static final String SETUP_HTML = "file:///android_asset/editor.html";public enum Type {BOLD,ITALIC,SUBSCRIPT,SUPERSCRIPT,STRIKETHROUGH,UNDERLINE,H1,H2,H3,H4,H5,H6,ORDEREDLIST,UNORDEREDLIST,JUSTIFYCENTER,JUSTIFYFULL,JUSTIFYLEFT,JUSTIFYRIGHT}@SuppressLint("SetJavaScriptEnabled")public RichEditor(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);setVerticalScrollBarEnabled(false);setHorizontalScrollBarEnabled(false);getSettings().setJavaScriptEnabled(true);setWebChromeClient(new WebChromeClient());setWebViewClient(createWebviewClient());loadUrl(SETUP_HTML);applyAttributes(context, attrs);}
}

其中​editor.html​即编辑器所展示的主页面

<!DOCTYPE html>
<html>
<head><meta name="viewport" content="user-scalable=no"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="normalize.css"><link rel="stylesheet" type="text/css" href="style.css">
</head>
<body><div id="editor" contenteditable="true"></div>
<script type="text/javascript" src="rich_editor.js"></script>
</body>
</html>

RichEditor控件中的函数对应着​rich_editor.js​中的接口

RichEditor:

public void setBold() {exec("javascript:RE.setBold();");}

​rich_editor.js:

RE.setBold = function() {document.execCommand('bold', false, null);RE.enabledEditingItems()
}

在布局中使用:

<com.text.richeditor.editor.RichEditorandroid:id="@+id/rich_Editor"android:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"android:overScrollMode="never" />

主要样式如下:
在这里插入图片描述
除了底部的功能栏可以使用,最左边还有一个排版按钮,这里主要是为了不方便弹出底部时,可以选择使用弹窗弹出功能栏,功能是一致的,可以选择性阉割。使用某一功能时会有颜色高亮提示。

3. 功能调用

首先要在activity中初始化控件,实现setOnDecorationChangeListener接口,监听点击某个功能按钮时显示对应高亮,让用户看到现在正在所使用的排版格式。

		//输入框显示字体的大小rich_Editor.setEditorFontSize(16)//输入框显示字体的颜色rich_Editor.setEditorFontColor(ContextCompat.getColor(this,R.color.deepGrey))//输入框背景设置rich_Editor.setEditorBackgroundColor(Color.WHITE)//输入框文本paddingrich_Editor.setPadding(10, 10, 10, 10)//输入提示文本rich_Editor.setPlaceholder("点击输入正文!~")rich_Editor.setOnDecorationChangeListener { _, types ->val flagArr = ArrayList<String>()for (i in types.indices) {flagArr.add(types[i].name)}if (flagArr.contains("BOLD")) {button_bold.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.colorPrimary))mEditorMenuFragment.updateActionStates(ActionType.BOLD, true)} else {button_bold.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.BOLD, false)}if (flagArr.contains("ITALIC")) {button_italic.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.colorPrimary))mEditorMenuFragment.updateActionStates(ActionType.ITALIC, true)} else {button_italic.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.ITALIC, false)}if (flagArr.contains("STRIKETHROUGH")) {button_strikethrough.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.colorPrimary))mEditorMenuFragment.updateActionStates(ActionType.STRIKETHROUGH, true)} else {button_strikethrough.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.STRIKETHROUGH, false)}if (flagArr.contains("JUSTIFYCENTER")) {button_align_center.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.colorPrimary))button_align_left.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))button_align_right.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_CENTER, true)mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_LEFT, false)mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_RIGHT, false)} else {button_align_center.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_CENTER, false)}if (flagArr.contains("JUSTIFYLEFT")) {button_align_center.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))button_align_left.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.colorPrimary))button_align_right.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_CENTER, false)mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_LEFT, true)mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_RIGHT, false)} else {button_align_left.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_LEFT, false)}if (flagArr.contains("JUSTIFYRIGHT")) {button_align_center.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))button_align_left.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))button_align_right.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.colorPrimary))mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_CENTER, false)mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_LEFT, false)mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_RIGHT, true)} else {button_align_right.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_RIGHT, false)}if (flagArr.contains("UNDERLINE")) {button_underline.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.colorPrimary))mEditorMenuFragment.updateActionStates(ActionType.UNDERLINE, true)} else {button_underline.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.UNDERLINE, false)}if (flagArr.contains("ORDEREDLIST")) {button_list_ol.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.colorPrimary))button_list_ul.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.ORDERED, true)mEditorMenuFragment.updateActionStates(ActionType.UNORDERED, false)} else {button_list_ol.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.ORDERED, false)}if (flagArr.contains("UNORDEREDLIST")) {button_list_ul.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.colorPrimary))button_list_ol.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.ORDERED, false)mEditorMenuFragment.updateActionStates(ActionType.UNORDERED, true)} else {button_list_ul.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.UNORDERED, false)}}

插入图片和视频:原本是调用特有的方法实现,但是可定制化不高,我就改成了插入html的形式

public void insertVideoPercentage(String url, String width, String height) {exec("javascript:RE.prepareInsert();");
//        exec("javascript:RE.insertVideoWH('" + url + "', '" + width + "', '" + height + "');");String testStr = "<video src=\"" + url + "\" width=\""+ width +"\"  height=\""+ height +"\" controls></video><br>";exec("javascript:RE.insertHTML('" + testStr + "');");}
public void insertImage(String url, String alt) {exec("javascript:RE.prepareInsert();");String testStr = "<img src=\"" + url + "\" alt=\"" + alt + "\" width=\"80%\"><br><br>";exec("javascript:RE.insertHTML('" + testStr + "');");}
	// 以下图片视频地址,来自网络素材fun selectImage(){// 进入相册选择照片之后可以本地文件直接插入html,或者上传到服务器获取地址再插入html中val path="https://upload-images.jianshu.io/upload_images/5809200-a99419bb94924e6d.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"againEdit()rich_Editor.insertImage(path, "dachshund")KeyBoardUtils.openKeyboard(edit_name, this@RichTextActivity)}fun selectVideo(){// 选择视频之后可以本地文件直接插入html,或者上传到服务器获取地址再插入html中val path="https://media.w3.org/2010/05/sintel/trailer.mp4"againEdit()rich_Editor.insertVideoPercentage(path, "80%","30%")KeyBoardUtils.openKeyboard(edit_name, this@RichTextActivity)}

图片删除:插入图片后点击图片可将图片删除:

@SuppressLint("ClickableViewAccessibility")public void setImageClickListener(ImageClickListener imageClickListener) {this.imageClickListener = imageClickListener;if (this.imageClickListener != null) {RichEditor.this.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {switch (event.getAction()) {case MotionEvent.ACTION_DOWN:DownX = (int) event.getX();DownY = (int) event.getY();moveX = 0;moveY = 0;currentMS = System.currentTimeMillis();//long currentMS     获取系统时间break;case MotionEvent.ACTION_MOVE:moveX += Math.abs(event.getX() - DownX);//X轴距离moveY += Math.abs(event.getY() - DownY);//y轴距离DownX = event.getX();DownY = event.getY();break;case MotionEvent.ACTION_UP:long moveTime = System.currentTimeMillis() - currentMS;//移动时间//判断是否继续传递信号if (moveTime < 400 && (moveX < 25 && moveY < 25)) {//这里是点击HitTestResult mResult = getHitTestResult();if (mResult != null) {final int type = mResult.getType();if (type == HitTestResult.IMAGE_TYPE) {//|| type == WebView.HitTestResult.IMAGE_ANCHOR_TYPE || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE//如果是点击图片String imageUrl = mResult.getExtra();setInputEnabled(false);postDelayed(new Runnable() {@Overridepublic void run() {if (imageClickListener != null) {if (imageUrl.contains("file://")) {//说明是本地文件去除String newImageUrl = imageUrl.replace("file://", "");imageClickListener.onImageClick(newImageUrl);} else {imageClickListener.onImageClick(imageUrl);}}}}, 200);} else {//不是点击的图片}}}break;}return false;}});}}
view.findViewById<View>(R.id.linear_delete_pic).setOnClickListener { v: View? ->//删除图片val removeUrl ="<img src=\"$currentUrl\" alt=\"dachshund\" width=\"80%\"><br>"val newUrl: String = rich_Editor.html.replace(removeUrl, "")currentUrl = ""rich_Editor.html = newUrlif (RichUtils.isEmpty(rich_Editor.html)) {rich_Editor.html = ""}popupWindow?.dismiss()}

插入链接:必须要先执行一次restorerange ,控制用户选择的文本范围或光标的当前位置

RE.restorerange = function(){var selection = window.getSelection();selection.removeAllRanges();var range = document.createRange();range.setStart(RE.currentSelection.startContainer, RE.currentSelection.startOffset);range.setEnd(RE.currentSelection.endContainer, RE.currentSelection.endOffset);selection.addRange(range);
}RE.insertLink = function(url, title) {RE.restorerange();var sel = document.getSelection();if (sel.toString().length == 0) {document.execCommand("insertHTML",false,"<a href='"+url+"'>"+title+"</a>");} else if (sel.rangeCount) {var el = document.createElement("a");el.setAttribute("href", url);el.setAttribute("title", title);var range = sel.getRangeAt(0).cloneRange();range.surroundContents(el);sel.removeAllRanges();sel.addRange(range);}RE.callback();
}

焦点的处理:

(1) 每一次调用排版功能都要调用一次,重新处理输入焦点,避免焦点冲突

private fun againEdit() {//如果第一次点击例如加粗,没有焦点时,获取焦点并弹出软键盘rich_Editor.focusEditor()KeyBoardUtils.openKeyboard(edit_name, this@RichTextActivity)}
public void focusEditor() {requestFocus();exec("javascript:RE.focus();");}
RE.focus = function() {var range = document.createRange();range.selectNodeContents(RE.editor);range.collapse(false);
//    var selection = window.getSelection();
//    selection.removeAllRanges();
//    selection.addRange(range);RE.editor.focus();
}

(2)这里弹出排版页面时必须同时弹出键盘,否则输入框的焦点消失,之前所设置的格式也会随之消失。比如我在底部点了个加粗效果,再点击排版弹窗时,加粗效果应该存在。但是一旦键盘关闭焦点消失,光标的效果也会被重置。
在这里插入图片描述

	KeyboardUtils.registerSoftInputChangedListener(this) { height: Int ->//键盘打开isKeyboardShowing = height > 0if (height > 0) {//fl_action.visibility = View.GONEval params = fl_action.layoutParamsparams.height = height/2fl_action.layoutParams = params} else{//if (fl_action.visibility != View.VISIBLE)fl_action.visibility = View.GONEiv_action.setColorFilter(ContextCompat.getColor(this@RichTextActivity, R.color.tintColor))}}iv_action.setOnClickListener {if (fl_action.visibility == View.VISIBLE) {fl_action.visibility = View.GONEiv_action.setColorFilter(ContextCompat.getColor(this@RichTextActivity, R.color.tintColor))} else {
//                if (isKeyboardShowing) {
//                    KeyboardUtils.hideSoftInput(this@RichTextActivity)
//                }KeyboardUtils.showSoftInput(this@RichTextActivity)fl_action.visibility = View.VISIBLEiv_action.setColorFilter(ContextCompat.getColor(this@RichTextActivity, R.color.colorPrimary))}}

主要的逻辑代码(RichTextActivity.kt):

class RichTextActivity :AppCompatActivity(), OnActionPerformListener {private var popupWindow //编辑图片的pop: CommonPopupWindow? = nullprivate var currentUrl=""private val mEditorMenuFragment by lazy{ EditorMenuFragment(R.id.fl_action) }private var isKeyboardShowing = falseprivate val inputLinkDialog by lazy { InputLinkDialog(this, sureListener = {href, name ->againEdit()rich_Editor.insertLink(href,name)}) }override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_rich_text)initData()}private fun initData(){initPop()initEditor()}private fun initEditor() {//输入框显示字体的大小rich_Editor.setEditorFontSize(16)//输入框显示字体的颜色rich_Editor.setEditorFontColor(ContextCompat.getColor(this,R.color.deepGrey))//输入框背景设置rich_Editor.setEditorBackgroundColor(Color.WHITE)//输入框文本paddingrich_Editor.setPadding(10, 10, 10, 10)//输入提示文本rich_Editor.setPlaceholder("点击输入正文!~")//文本输入框监听事件rich_Editor.setOnTextChangeListener { text -> Log.e("富文本文字变动", text!!) }edit_name.addTextChangedListener(object : TextWatcher {override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}override fun afterTextChanged(s: Editable) {tv_sum.text = edit_name.text.toString().length.toString()+"/100"val html = rich_Editor.html}})rich_Editor.setOnDecorationChangeListener { _, types ->val flagArr = ArrayList<String>()for (i in types.indices) {flagArr.add(types[i].name)}if (flagArr.contains("BOLD")) {button_bold.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.colorPrimary))mEditorMenuFragment.updateActionStates(ActionType.BOLD, true)} else {button_bold.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.BOLD, false)}if (flagArr.contains("ITALIC")) {button_italic.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.colorPrimary))mEditorMenuFragment.updateActionStates(ActionType.ITALIC, true)} else {button_italic.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.ITALIC, false)}if (flagArr.contains("STRIKETHROUGH")) {button_strikethrough.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.colorPrimary))mEditorMenuFragment.updateActionStates(ActionType.STRIKETHROUGH, true)} else {button_strikethrough.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.STRIKETHROUGH, false)}if (flagArr.contains("JUSTIFYCENTER")) {button_align_center.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.colorPrimary))button_align_left.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))button_align_right.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_CENTER, true)mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_LEFT, false)mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_RIGHT, false)} else {button_align_center.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_CENTER, false)}if (flagArr.contains("JUSTIFYLEFT")) {button_align_center.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))button_align_left.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.colorPrimary))button_align_right.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_CENTER, false)mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_LEFT, true)mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_RIGHT, false)} else {button_align_left.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_LEFT, false)}if (flagArr.contains("JUSTIFYRIGHT")) {button_align_center.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))button_align_left.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))button_align_right.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.colorPrimary))mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_CENTER, false)mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_LEFT, false)mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_RIGHT, true)} else {button_align_right.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.JUSTIFY_RIGHT, false)}if (flagArr.contains("UNDERLINE")) {button_underline.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.colorPrimary))mEditorMenuFragment.updateActionStates(ActionType.UNDERLINE, true)} else {button_underline.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.UNDERLINE, false)}if (flagArr.contains("ORDEREDLIST")) {button_list_ol.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.colorPrimary))button_list_ul.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.ORDERED, true)mEditorMenuFragment.updateActionStates(ActionType.UNORDERED, false)} else {button_list_ol.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.ORDERED, false)}if (flagArr.contains("UNORDEREDLIST")) {button_list_ul.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.colorPrimary))button_list_ol.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.ORDERED, false)mEditorMenuFragment.updateActionStates(ActionType.UNORDERED, true)} else {button_list_ul.setColorFilter(ContextCompat.getColor(this@RichTextActivity,R.color.tintColor))mEditorMenuFragment.updateActionStates(ActionType.UNORDERED, false)}}rich_Editor.setImageClickListener { imageUrl ->currentUrl = imageUrlpopupWindow?.showBottom(ll_container, 0.5f)}button_rich_do.setOnClickListener { rich_Editor.redo() }button_rich_undo.setOnClickListener { rich_Editor.undo()}button_bold.setOnClickListener {againEdit()rich_Editor.setBold() }button_underline.setOnClickListener {againEdit()rich_Editor.setUnderline()}button_italic.setOnClickListener {againEdit()rich_Editor.setItalic()}button_strikethrough.setOnClickListener {againEdit()rich_Editor.setStrikeThrough()}//字号button_h1.setOnClickListener {againEdit()rich_Editor.setFontSize(2)}button_h2.setOnClickListener {againEdit()rich_Editor.setFontSize(3)}button_h3.setOnClickListener {againEdit()rich_Editor.setFontSize(4)}button_h4.setOnClickListener {againEdit()rich_Editor.setFontSize(5)}button_indent_decrease.setOnClickListener {againEdit()rich_Editor.setOutdent()}button_indent_increase.setOnClickListener {againEdit()rich_Editor.setIndent()}button_list_ul.setOnClickListener {againEdit()rich_Editor.setBullets()}button_list_ol.setOnClickListener {againEdit()rich_Editor.setNumbers()}button_align_center.setOnClickListener {againEdit()rich_Editor.setAlignCenter()}button_align_left.setOnClickListener {againEdit()rich_Editor.setAlignLeft()}button_align_right.setOnClickListener {againEdit()rich_Editor.setAlignRight()}button_link.setOnClickListener {KeyboardUtils.hideSoftInput(this@RichTextActivity)inputLinkDialog.show()}//选择图片button_image.setOnClickListener {selectImage()}//选择视频button_video.setOnClickListener {selectVideo()}mEditorMenuFragment.setActionClickListener(this)supportFragmentManager.beginTransaction().add(R.id.fl_action, mEditorMenuFragment, EditorMenuFragment::class.java.name).commit()KeyboardUtils.registerSoftInputChangedListener(this) { height: Int ->//键盘打开isKeyboardShowing = height > 0if (height > 0) {//fl_action.visibility = View.GONEval params = fl_action.layoutParamsparams.height = height/2fl_action.layoutParams = params} else{//if (fl_action.visibility != View.VISIBLE)fl_action.visibility = View.GONEiv_action.setColorFilter(ContextCompat.getColor(this@RichTextActivity, R.color.tintColor))}}iv_action.setOnClickListener {if (fl_action.visibility == View.VISIBLE) {fl_action.visibility = View.GONEiv_action.setColorFilter(ContextCompat.getColor(this@RichTextActivity, R.color.tintColor))} else {
//                if (isKeyboardShowing) {
//                    KeyboardUtils.hideSoftInput(this@RichTextActivity)
//                }KeyboardUtils.showSoftInput(this@RichTextActivity)fl_action.visibility = View.VISIBLEiv_action.setColorFilter(ContextCompat.getColor(this@RichTextActivity, R.color.colorPrimary))}}}private fun initPop() {val view= LayoutInflater.from(this@RichTextActivity).inflate(R.layout.pop_picture, null)view.findViewById<View>(R.id.linear_cancle).setOnClickListener { popupWindow?.dismiss() }view.findViewById<View>(R.id.linear_delete_pic).setOnClickListener { v: View? ->//删除图片val removeUrl ="<img src=\"$currentUrl\" alt=\"dachshund\" width=\"80%\"><br>"val newUrl: String = rich_Editor.html.replace(removeUrl, "")currentUrl = ""rich_Editor.html = newUrlif (RichUtils.isEmpty(rich_Editor.html)) {rich_Editor.html = ""}popupWindow?.dismiss()}popupWindow = CommonPopupWindow.Builder(this@RichTextActivity).setView(view).setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT).setOutsideTouchable(true) //在外不可用手指取消.setAnimationStyle(R.style.pop_animation) //设置popWindow的出场动画.create()popupWindow?.setOnDismissListener(PopupWindow.OnDismissListener {rich_Editor.setInputEnabled(true)})}private fun againEdit() {//如果第一次点击例如加粗,没有焦点时,获取焦点并弹出软键盘rich_Editor.focusEditor()KeyBoardUtils.openKeyboard(edit_name, this@RichTextActivity)}override fun onActionPerform(type: ActionType?, vararg values: Any?) {var value = ""if (values != null && values.isNotEmpty()) {value = values[0] as String}againEdit()when (type) {ActionType.FORE_COLOR -> { rich_Editor.setTextColor(value)}ActionType.BOLD -> { rich_Editor.setBold()}ActionType.ITALIC -> rich_Editor.setItalic()ActionType.UNDERLINE -> rich_Editor.setUnderline()ActionType.STRIKETHROUGH -> rich_Editor.setStrikeThrough()ActionType.H1 -> {rich_Editor.setFontSize(2)mEditorMenuFragment.updateActionStates(ActionType.H1,true)mEditorMenuFragment.updateActionStates(ActionType.H2,false)mEditorMenuFragment.updateActionStates(ActionType.H3,false)mEditorMenuFragment.updateActionStates(ActionType.H4,false)}ActionType.H2 -> {rich_Editor.setFontSize(3)mEditorMenuFragment.updateActionStates(ActionType.H1,false)mEditorMenuFragment.updateActionStates(ActionType.H2,true)mEditorMenuFragment.updateActionStates(ActionType.H3,false)mEditorMenuFragment.updateActionStates(ActionType.H4,false)}ActionType.H3 -> {rich_Editor.setFontSize(4)mEditorMenuFragment.updateActionStates(ActionType.H1,false)mEditorMenuFragment.updateActionStates(ActionType.H2,false)mEditorMenuFragment.updateActionStates(ActionType.H3,true)mEditorMenuFragment.updateActionStates(ActionType.H4,false)}ActionType.H4 -> {rich_Editor.setFontSize(5)mEditorMenuFragment.updateActionStates(ActionType.H1,false)mEditorMenuFragment.updateActionStates(ActionType.H2,false)mEditorMenuFragment.updateActionStates(ActionType.H3,false)mEditorMenuFragment.updateActionStates(ActionType.H4,true)}ActionType.JUSTIFY_LEFT -> rich_Editor.setAlignLeft()ActionType.JUSTIFY_CENTER -> rich_Editor.setAlignCenter()ActionType.JUSTIFY_RIGHT -> rich_Editor.setAlignRight()ActionType.INDENT -> rich_Editor.setIndent()ActionType.OUTDENT -> rich_Editor.setOutdent()ActionType.UNORDERED->rich_Editor.setBullets()ActionType.ORDERED->rich_Editor.setNumbers()ActionType.IMAGE -> {selectImage()}ActionType.LINK -> {KeyboardUtils.hideSoftInput(this@RichTextActivity)inputLinkDialog.show()}ActionType.VIDEO -> {selectVideo()}else -> {}}}// 以下图片视频地址,来自网络素材fun selectImage(){// 进入相册选择照片之后可以本地文件直接插入html,或者上传到服务器获取地址再插入html中val path="https://upload-images.jianshu.io/upload_images/5809200-a99419bb94924e6d.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"againEdit()rich_Editor.insertImage(path, "dachshund")KeyBoardUtils.openKeyboard(edit_name, this@RichTextActivity)}fun selectVideo(){// 选择视频之后可以本地文件直接插入html,或者上传到服务器获取地址再插入html中val path="https://media.w3.org/2010/05/sintel/trailer.mp4"againEdit()rich_Editor.insertVideoPercentage(path, "80%","30%")KeyBoardUtils.openKeyboard(edit_name, this@RichTextActivity)}
}

4. 完整代码

完整代码我已上传github,需要的可以自行pull:https://github.com/FullCourage/RichEditor


总结

这个功能是之前做的,时间间隔有点久了,有些细微的点已经记不得了,由此事后的总结记录就格外重要。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/26457.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

幸狐RV1106开发板烧录Ubuntu系统与配置SDK,RV1106 LuckFox Pico Max——最新的操作

资料&#xff1a;上手教程 | LUCKFOX WIKI 以及SDK内的文档资料 开发板型号&#xff1a;RV1106 LuckFox Pico Max 烧录系统&#xff1a; Ubuntu 虚拟机系统&#xff1a;Ubuntu 20.04&&Ubuntu22.04 PC系统&#xff1a;win11 占用空间&#xff1a;大概15G 本文主要记…

解决IDEA报错Could not find resource mybatis-config.xml最全排错解决收录

解决IDEA报错:Could not find resource mybatis-config.xml最全排错解决收录 1.问题产生 迁移新项目的Java web开发测试数据库时IDEA爆Could not find resource mybatis-config.xml 这个错误表明Mybatis无法找到名为mybatis-config.xml的配置文件。 需要确保该文件存在于cla…

【Qt 学习笔记】Qt窗口 | 对话框 | 创建自定义对话框

博客主页&#xff1a;Duck Bro 博客主页系列专栏&#xff1a;Qt 专栏关注博主&#xff0c;后期持续更新系列文章如果有错误感谢请大家批评指出&#xff0c;及时修改感谢大家点赞&#x1f44d;收藏⭐评论✍ Qt窗口 | 对话框 | 创建自定义对话框 文章编号&#xff1a;Qt 学习笔记…

鸿蒙轻内核A核源码分析系列七 进程管理 (3)

本文记录下进程相关的初始化函数&#xff0c;如OsSystemProcessCreate、OsProcessInit、OsProcessCreateInit、OsUserInitProcess、OsDeInitPCB、OsUserInitProcessStart等。 1、LiteOS-A内核进程创建初始化通用函数 先看看一些内部函数&#xff0c;不管是初始化用户态进程还…

Spring 内置BeanPostProcessor 的子子孙孙

Spring 框架已经实现了很多BeanPostProcessor的类&#xff0c;如下是关于BeanPostProcessor 的类图&#xff0c;图片过大&#xff0c;可以下载资源包看。 要能说清楚这些类&#xff0c;挺难&#xff0c;我也不知道怎么写&#xff0c;这几个类都分布在不同的包中&#xff0c;我感…

Spring系统学习 - Bean的作用域

bean作用域介绍 Spring框架提供了不同的作用域来管理Bean的生命周期和可见性&#xff0c;这对于控制不同类型的组件和处理并发请求尤其重要。 singleton&#xff08;默认&#xff09;&#xff1a; 每个Spring IoC容器只有一个bean实例。当容器创建bean后&#xff0c;它会被缓存…

C#聊天室①

聊天室服务器&#xff1a; 创建项目 桌面不需要使用控件 Program.cs internal class Program {static TcpListener server;[STAThread]static void Main(){Program p new Program(); p.start();}void start(){server new TcpListener(IPAddress.Parse(GetIP()), 33…

iText7——画发票PDF(完整)

显示描述&#xff1a; 1、每页显示必须带有发票头、“销售方和购买方信息” 2、明细填充为&#xff1a;当n≤8 行时&#xff0c;发票总高度140mm&#xff0c;每条发票明细行款高度4.375mm&#xff1b; 当8<n≤12行时&#xff0c;发票高度增加17.5mm&#xff0c;不换页&#…

【模拟-BM100 设计LRU缓存结构】

题目 BM100 设计LRU缓存结构 描述 设计LRU(最近最少使用)缓存结构&#xff0c;该结构在构造时确定大小&#xff0c;假设大小为 capacity &#xff0c;操作次数是 n &#xff0c;并有如下功能: Solution(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存get(key)&am…

【PyTorch 新手基础】Regularization -- 减轻过拟合 overfitting

Overfit 过拟合&#xff0c;效果如最右图所示 常见应对方案如下&#xff1a; 增大数据集入手&#xff1a;More data or data argumentation简化模型参数入手&#xff1a;Constraint model complexity (shallow model, regularization) or dropout dropout: torch.nn.Dropout(0…

搭建一个好玩的 RSS 订阅网站记录

全文相关链接 Github仓库创建链接Railway官网Supabase官网f-droid上的co.appreactor.news应用下载链接Railway账户使用量估算链接 全文相关代码 原文地址: https://blog.taoshuge.eu.org/p/270/ Dockerfile FROM docker.io/miniflux/miniflux:2.1.3环境变量 DATABASE_URL…

Java线程池参数和处理流程

线程池是一种管理和重用线程资源的机制&#xff0c;是利用池化思想设置和管理多线程的工具。线程池维护一定数量的线程&#xff0c;当有任务需要时&#xff0c;就从中选择一个的线程用来执行任务&#xff0c;当使用完成后该线程就会被重新放回线程池中&#xff0c;通过这样循环…

Apollo配置中心最佳实践

携程配置中心地址&#xff1a;GitCode - 全球开发者的开源社区,开源代码托管平台 1.1 Apollo配置中心介绍 Apollo&#xff08;阿波罗&#xff09;是开源配置管理中心&#xff0c;能够集中化管理应用不同环境、不同集群的配置&#xff0c;配置修改后能够实时推送到应用端…

ASM字节码插桩实现点击防抖

思路&#xff1a;在点击事件onclick的时候&#xff0c;将view的onclick在给定的时间给拦截掉。以前我们可能都是用一个util来拦截&#xff0c;这样在每个点击事件都得去判断&#xff0c;那么这里就用字节码插桩的形式来实现一下。 ASM的引入 dependencies {implementation gr…

QT day01

思维导图 QT编程 实现一个账号登录界面 代码&#xff1a; myweidget.h #ifndef MYWEIDGET_H #define MYWEIDGET_H#include <QWidget> #include <QIcon> //图标类 #include <QLineEdit> //行编辑器类 #include <QLabel> //标签类 #…

【Redis】安装和命令行客户端

https://www.bilibili.com/video/BV1cr4y1671t https://www.oz6.cn/articles/58 redis 非结构化有&#xff1a; 键值类型(Redis)文档类型(MongoDB)列类型(HBase)Graph:类型(Neo4j) 扩展性&#xff1a;水平即为分布式扩展 redis特征 键值&#xff08;key-value&#xff09;型…

【springBoot学习篇】springBoot集成mybatis

目录 第一步&#xff1a;新建spring项目的时候&#xff0c;需要勾选mybatis框架和jdbc连接数据库的包 第二步&#xff1a;在resource目录下面的配置文件当中添加以下的内容&#xff1a;配置数据源 第三步&#xff1a;配置实体类 第四步&#xff1a;添加一个对象的增删改查方…

上位机图像处理和嵌入式模块部署(h750 mcu和图像处理)

【 声明&#xff1a;版权所有&#xff0c;欢迎转载&#xff0c;请勿用于商业用途。 联系信箱&#xff1a;feixiaoxing 163.com】 前面我们说过&#xff0c;h750和之前的103、407相比较&#xff0c;本身cpu频率比较高&#xff0c;flash大小一般&#xff0c;但是ram比较大&#x…

群辉其它方案远程访问(ZeroTier篇)

目录 1、注册ZeroTier 2、创建网络 3、下载安装客户端 (1)Windows (2)移动端 i.Android i.iOS (a)注册新ID (b)登陆苹果应用商店 iii.群辉NAS 4、客户端加入网络 (a)Windows (b)Android (c)群辉NAS 5、使用 群辉的远程访问,最标准的做法就是使用…

自动控制原理【期末复习】(二)

无人机上桨之后可以在调试架上先调试&#xff1a; 1.根轨迹的绘制 /// 前面针对的是时域分析&#xff0c;下面针对频域分析&#xff1a; 2.波特图 3.奈维斯特图绘制 1.奈氏稳定判据 2.对数稳定判据 3.相位裕度和幅值裕度