├── .gitignore ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── zhou │ │ └── demo │ │ └── ApplicationTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── assets │ │ └── doge.jpg │ ├── java │ │ └── zhou │ │ │ └── demo │ │ │ ├── DebugActivity.java │ │ │ ├── GifActivity.java │ │ │ ├── ListViewActivity.java │ │ │ ├── MainActivity.java │ │ │ ├── RecyclerViewActivity.java │ │ │ └── TestActivity.java │ └── res │ │ ├── drawable │ │ ├── sl.jpg │ │ └── test.xml │ │ ├── layout │ │ ├── activity_debug.xml │ │ ├── activity_list.xml │ │ ├── activity_main.xml │ │ ├── activity_recycler.xml │ │ ├── activity_test.xml │ │ └── item_list.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── raw │ │ ├── hello.md │ │ ├── large │ │ ├── sl.jpg │ │ └── tt.md │ │ ├── values-w820dp │ │ └── dimens.xml │ │ ├── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ │ └── xml │ │ └── network_security_config.xml │ └── test │ └── java │ └── zhou │ └── demo │ └── ExampleUnitTest.java ├── build.gradle ├── glideimagegetter ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── zzhoujay │ │ │ └── glideimagegetter │ │ │ ├── GlideImageGetter.java │ │ │ ├── ImageTarget.java │ │ │ ├── ImageTargetBitmap.java │ │ │ └── ImageTargetGif.java │ └── res │ │ └── values │ │ └── zhou_glide_ids.xml │ └── test │ └── java │ └── com │ └── zzhoujay │ └── glideimagegetter │ └── ExampleUnitTest.java ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── image └── image.jpg ├── okhttpimagedownloader ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ └── java │ └── com │ └── zzhoujay │ └── okhttpimagedownloader │ └── OkHttpImageDownloader.java ├── richtext ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── zzhoujay │ │ └── richtext │ │ ├── CacheType.java │ │ ├── ImageHolder.java │ │ ├── LinkHolder.java │ │ ├── RichState.java │ │ ├── RichText.java │ │ ├── RichTextConfig.java │ │ ├── RichTextPool.java │ │ ├── RichType.java │ │ ├── cache │ │ ├── BitmapPool.java │ │ └── CacheIOHelper.java │ │ ├── callback │ │ ├── BitmapStream.java │ │ ├── Callback.java │ │ ├── Closeable.java │ │ ├── DrawableGetter.java │ │ ├── ImageFixCallback.java │ │ ├── ImageGetter.java │ │ ├── ImageLoadNotify.java │ │ ├── LinkFixCallback.java │ │ ├── OnImageClickListener.java │ │ ├── OnImageLongClickListener.java │ │ ├── OnUrlClickListener.java │ │ ├── OnUrlLongClickListener.java │ │ ├── Recyclable.java │ │ └── SimpleImageFixCallback.java │ │ ├── drawable │ │ ├── DrawableBorderHolder.java │ │ ├── DrawableSizeHolder.java │ │ ├── DrawableWrapper.java │ │ └── GifDrawable.java │ │ ├── exceptions │ │ ├── BitmapCacheException.java │ │ ├── BitmapCacheLoadFailureException.java │ │ ├── BitmapCacheNotFoundException.java │ │ ├── BitmapInputStreamNullPointException.java │ │ ├── HttpResponseCodeException.java │ │ ├── ImageDecodeException.java │ │ ├── ImageDownloadTaskAddFailureException.java │ │ ├── ImageDownloaderNonExistenceException.java │ │ ├── ImageLoadCancelledException.java │ │ ├── ImageWrapperMultiSourceException.java │ │ └── ResetImageSourceException.java │ │ ├── ext │ │ ├── Base64.java │ │ ├── ContextKit.java │ │ ├── Debug.java │ │ ├── HtmlTagHandler.java │ │ ├── ImageKit.java │ │ ├── LongClickableLinkMovementMethod.java │ │ ├── MD5.java │ │ └── TextKit.java │ │ ├── ig │ │ ├── AbstractImageLoader.java │ │ ├── AssetsImageLoader.java │ │ ├── Base64ImageLoader.java │ │ ├── CallbackImageLoader.java │ │ ├── Cancelable.java │ │ ├── DefaultImageDownloader.java │ │ ├── DefaultImageGetter.java │ │ ├── FutureCancelableWrapper.java │ │ ├── ImageDownloader.java │ │ ├── ImageDownloaderManager.java │ │ ├── ImageLoader.java │ │ ├── ImageWrapper.java │ │ ├── InputStreamImageLoader.java │ │ ├── LocalFileImageLoader.java │ │ └── SourceDecode.java │ │ ├── parser │ │ ├── CachedSpannedParser.java │ │ ├── Html2SpannedParser.java │ │ ├── ImageGetterWrapper.java │ │ ├── Markdown2SpannedParser.java │ │ └── SpannedParser.java │ │ └── spans │ │ ├── Clickable.java │ │ ├── ClickableImageSpan.java │ │ ├── LongClickable.java │ │ ├── LongClickableSpan.java │ │ └── LongClickableURLSpan.java │ └── res │ └── values │ └── zhou_ids.xml └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### JetBrains template 3 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio 4 | 5 | *.iml 6 | 7 | ## Directory-based project format: 8 | .idea/ 9 | # if you remove the above rule, at least ignore the following: 10 | 11 | # User-specific stuff: 12 | # .idea/workspace.xml 13 | # .idea/tasks.xml 14 | # .idea/dictionaries 15 | 16 | # Sensitive or high-churn files: 17 | # .idea/dataSources.ids 18 | # .idea/dataSources.xml 19 | # .idea/sqlDataSources.xml 20 | # .idea/dynamic.xml 21 | # .idea/uiDesigner.xml 22 | 23 | # Gradle: 24 | # .idea/gradle.xml 25 | # .idea/libraries 26 | 27 | # Mongo Explorer plugin: 28 | # .idea/mongoSettings.xml 29 | 30 | ## File-based project format: 31 | *.ipr 32 | *.iws 33 | 34 | ## Plugin-specific files: 35 | 36 | # IntelliJ 37 | /out/ 38 | 39 | # mpeltonen/sbt-idea plugin 40 | .idea_modules/ 41 | 42 | # JIRA plugin 43 | atlassian-ide-plugin.xml 44 | 45 | # Crashlytics plugin (for Android Studio and IntelliJ) 46 | com_crashlytics_export_strings.xml 47 | crashlytics.properties 48 | crashlytics-build.properties 49 | ### NetBeans template 50 | nbproject/private/ 51 | build/ 52 | nbbuild/ 53 | dist/ 54 | nbdist/ 55 | nbactions.xml 56 | nb-configuration.xml 57 | .nb-gradle/ 58 | ### Java template 59 | *.class 60 | 61 | # Mobile Tools for Java (J2ME) 62 | .mtj.tmp/ 63 | 64 | # Package Files # 65 | *.jar 66 | *.war 67 | *.ear 68 | 69 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 70 | hs_err_pid* 71 | ### Linux template 72 | *~ 73 | 74 | # KDE directory preferences 75 | .directory 76 | 77 | # Linux trash folder which might appear on any partition or disk 78 | .Trash-* 79 | ### OSX template 80 | .DS_Store 81 | .AppleDouble 82 | .LSOverride 83 | 84 | # Icon must end with two \r 85 | Icon 86 | 87 | # Thumbnails 88 | ._* 89 | 90 | # Files that might appear in the root of a volume 91 | .DocumentRevisions-V100 92 | .fseventsd 93 | .Spotlight-V100 94 | .TemporaryItems 95 | .Trashes 96 | .VolumeIcon.icns 97 | 98 | # Directories potentially created on remote AFP share 99 | .AppleDB 100 | .AppleDesktop 101 | Network Trash Folder 102 | Temporary Items 103 | .apdisk 104 | ### Windows template 105 | # Windows image file caches 106 | Thumbs.db 107 | ehthumbs.db 108 | 109 | # Folder config file 110 | Desktop.ini 111 | 112 | # Recycle Bin used on file shares 113 | $RECYCLE.BIN/ 114 | 115 | # Windows Installer files 116 | *.cab 117 | *.msi 118 | *.msm 119 | *.msp 120 | 121 | # Windows shortcuts 122 | *.lnk 123 | ### Maven template 124 | target/ 125 | pom.xml.tag 126 | pom.xml.releaseBackup 127 | pom.xml.versionsBackup 128 | pom.xml.next 129 | release.properties 130 | dependency-reduced-pom.xml 131 | buildNumber.properties 132 | .mvn/timing.properties 133 | ### Android template 134 | # Built application files 135 | *.apk 136 | *.ap_ 137 | 138 | # Files for the Dalvik VM 139 | *.dex 140 | 141 | # Java class files 142 | 143 | # Generated files 144 | bin/ 145 | gen/ 146 | 147 | # Gradle files 148 | .gradle/ 149 | 150 | # Local configuration file (sdk path, etc) 151 | local.properties 152 | 153 | # Proguard folder generated by Eclipse 154 | proguard/ 155 | 156 | # Log Files 157 | *.log 158 | 159 | # Android Studio Navigation editor temp files 160 | .navigation/ 161 | ### Eclipse template 162 | *.pydevproject 163 | .metadata 164 | .gradle 165 | tmp/ 166 | *.tmp 167 | *.bak 168 | *.swp 169 | *~.nib 170 | .settings/ 171 | .loadpath 172 | 173 | # Eclipse Core 174 | .project 175 | 176 | # External tool builders 177 | .externalToolBuilders/ 178 | 179 | # Locally stored "Eclipse launch configurations" 180 | *.launch 181 | 182 | # CDT-specific 183 | .cproject 184 | 185 | # JDT-specific (Eclipse Java Development Tools) 186 | .classpath 187 | 188 | # Java annotation processor (APT) 189 | .factorypath 190 | 191 | # PDT-specific 192 | .buildpath 193 | 194 | # sbteclipse plugin 195 | .target 196 | 197 | # TeXlipse plugin 198 | .texlipse 199 | ### JDeveloper template 200 | # default application storage directory used by the IDE Performance Cache feature 201 | .data/ 202 | 203 | # used for ADF styles caching 204 | temp/ 205 | 206 | # default output directories 207 | classes/ 208 | deploy/ 209 | javadoc/ 210 | 211 | # lock file, a part of Oracle Credential Store Framework 212 | cwallet.sso.lck### Gradle template 213 | 214 | # Ignore Gradle GUI config 215 | gradle-app.setting 216 | 217 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 218 | !gradle-wrapper.jar 219 | 220 | publish.sh 221 | captures/ 222 | glideimagegetter/libs/ 223 | projectFilesBackup/ 224 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 zzhoujay 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RichText-AndroidX 2 | 3 | ### 注意:原项目作者已经不维护了,不支持AndroidX,此项目使用原作者代码改造为支持Androidx 4 | 5 | > Android平台下的富文本解析器 6 | 7 | * 流式操作 8 | * 低侵入性 9 | * 依赖少,只依赖了`disklrucache`和`support v4` 10 | * 支持Html和Markdown格式文本 11 | * 支持图片点击和长按事件 12 | * 链接点击事件和长按事件 13 | * 支持设置加载中和加载错误时的图片 14 | * 支持自定义超链接的点击回调 15 | * 支持修正图片宽高 16 | * 支持GIF图片 17 | * 支持Base64编码、本地图片和Assets目录图片 18 | * 自持自定义图片加载器、图片加载器 19 | * 支持内存和磁盘双缓存 20 | * 已经加入对自定义Html解析器的支持 21 | 22 | ### 效果 23 | 24 | ![演示](image/image.jpg "演示") 25 | 26 | 27 | ### 引入方法 28 | 29 | clone 该项目然后跑起来,打出 aar包然后引入自己的项目 30 | 31 | 32 | 新Html解析器增加了对代码块的支持,代码块可以触发点击事件,通过`urlClick`设置, 33 | 代码块回调的参数由`code://`开头 34 | 35 | 使用新Html解析器遇到问题请在[https://github.com/zzhoujay/Htm](https://github.com/zzhoujay/Html)提issue 36 | 37 | ### 关于issue 38 | 39 | 最近一段时间会比较忙,issue不能及时处理,一般会定时抽空集中解决issue,但时间有限解决速度上不敢保证。 40 | 41 | 欢迎提交pull request帮助完善这个项目 42 | 43 | ### 注意 44 | 45 | 在第一次调用RichText之前先调用`RichText.initCacheDir()`方法设置缓存目录 46 | 47 | ImageFixCallback的回调方法不一定是在主线程回调,注意不要进行UI操作 48 | 49 | 本地图片由根路径`\`开头,Assets目录图片由`file:///android_asset/`开头 50 | 51 | Gif图片播放不支持硬件加速,若要使用Gif图片请先关闭TextView的硬件加速 52 | ``` 53 | textView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); 54 | ``` 55 | 56 | ### 使用方式 57 | 58 | [多看wiki](https://github.com/zzhoujay/RichText/wiki)、[多看wiki](https://github.com/zzhoujay/RichText/wiki)、[多看wiki](https://github.com/zzhoujay/RichText/wiki),重要的事情说三遍 59 | 60 | ### 关于自定义的Html解析器 61 | 62 | Html解析器子项目:[Html](https://github.com/zzhoujay/Htm) 63 | 64 | ### 关于Markdown 65 | 66 | Markdown源于子项目:[Markdown](https://github.com/zzhoujay/Markdown) 67 | 68 | 若在markdown解析过程中发现什么问题可以在该项目中反馈 69 | 70 | ### 关于富文本编辑器 71 | 72 | 编辑器开发已暂停,[RichEditor](https://github.com/zzhoujay/RichEditor) 73 | 74 | ### 具体使用请查看demo 75 | 76 | [ListView Demo](https://github.com/zzhoujay/RichText/blob/master/app/src/main/java/zhou/demo/ListViewActivity.java)、 77 | [RecyclerView Demo](https://github.com/zzhoujay/RichText/blob/master/app/src/main/java/zhou/demo/RecyclerViewActivity.java)、 78 | [Gif Demo](https://github.com/zzhoujay/RichText/blob/master/app/src/main/java/zhou/demo/GifActivity.java) 79 | 80 | 81 | ### License 82 | 83 | ``` 84 | The MIT License (MIT) 85 | 86 | Copyright (c) 2016 zzhoujay 87 | 88 | Permission is hereby granted, free of charge, to any person obtaining a copy 89 | of this software and associated documentation files (the "Software"), to deal 90 | in the Software without restriction, including without limitation the rights 91 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 92 | copies of the Software, and to permit persons to whom the Software is 93 | furnished to do so, subject to the following conditions: 94 | 95 | The above copyright notice and this permission notice shall be included in all 96 | copies or substantial portions of the Software. 97 | 98 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 99 | 100 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 101 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 102 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 103 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 104 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 105 | SOFTWARE. 106 | ``` 107 | 108 | _by zzhoujay_ 109 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdk 33 5 | defaultConfig { 6 | applicationId "zhou.demo" 7 | minSdkVersion 21 8 | targetSdkVersion 33 9 | versionCode 1 10 | versionName "1.0" 11 | } 12 | buildTypes { 13 | release { 14 | minifyEnabled false 15 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 16 | } 17 | } 18 | productFlavors { 19 | } 20 | namespace 'zhou.demo' 21 | lint { 22 | abortOnError false 23 | } 24 | } 25 | 26 | dependencies { 27 | implementation fileTree(include: ['*.jar'], dir: 'libs') 28 | testImplementation 'junit:junit:4.13.2' 29 | // appcompat 1.7.0 会强制 compile = 34 这里先用 1.6.1 30 | implementation 'androidx.appcompat:appcompat:1.6.1' 31 | implementation 'androidx.recyclerview:recyclerview:1.3.2' 32 | implementation project(':richtext') 33 | // implementation project(':okhttpimagedownloader') 34 | // implementation 'com.zzhoujay.richtext:richtext:3.0.8' 35 | implementation 'com.zzhoujay:html:1.0.2' 36 | } 37 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /home/zhou/Android/Sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/androidTest/java/zhou/demo/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package zhou.demo; 2 | 3 | import android.app.Application; 4 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 15 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /app/src/main/assets/doge.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/L-X-J/RichText-Androidx/e81cb12ecc3a14047b0c54fe79b1e10fee41b646/app/src/main/assets/doge.jpg -------------------------------------------------------------------------------- /app/src/main/java/zhou/demo/DebugActivity.java: -------------------------------------------------------------------------------- 1 | package zhou.demo; 2 | 3 | import android.app.Activity; 4 | import android.os.Bundle; 5 | import androidx.annotation.Nullable; 6 | import android.util.Log; 7 | import android.widget.ImageView; 8 | import android.widget.TextView; 9 | 10 | import com.zzhoujay.richtext.ImageHolder; 11 | import com.zzhoujay.richtext.RichText; 12 | import com.zzhoujay.richtext.callback.Callback; 13 | import com.zzhoujay.richtext.callback.SimpleImageFixCallback; 14 | 15 | /** 16 | * Created by zhou on 2017/10/8. 17 | */ 18 | 19 | public class DebugActivity extends Activity { 20 | 21 | private static final String TAG = "DebugActivity"; 22 | 23 | @Override 24 | protected void onCreate(@Nullable Bundle savedInstanceState) { 25 | super.onCreate(savedInstanceState); 26 | setContentView(R.layout.activity_debug); 27 | 28 | RichText.initCacheDir(this); 29 | RichText.debugMode = true; 30 | 31 | TextView textView = findViewById(R.id.test_text); 32 | ImageView imageView = findViewById(R.id.image_view); 33 | 34 | String test_text_2 = "

我是文本内容 下一个" + 35 | "似懂非懂撒范德萨咖啡机盛大开放惊世毒妃

我是文本内容 下一个" + 36 | "似懂非懂撒范德萨咖啡机盛大开放惊世毒妃

我是文本内容 下一个" + 37 | "似懂非懂撒范德萨咖啡机盛大开放惊世毒妃

我是文本内容 下一个" + 38 | "似懂非懂撒范德萨咖啡机盛大开放惊世毒妃

似懂非懂撒范德萨咖啡机盛大开放惊世毒妃"; 39 | 40 | String test_text_1 = "

Test1

"; 41 | 42 | 43 | RichText.from(test_text_2) 44 | .showBorder(true) 45 | .fix(new SimpleImageFixCallback() { 46 | 47 | @Override 48 | public void onFailure(ImageHolder holder, Exception e) { 49 | super.onFailure(holder, e); 50 | e.printStackTrace(); 51 | } 52 | }) 53 | .done(new Callback() { 54 | @Override 55 | public void done(boolean imageLoadDone) { 56 | Log.d(TAG, "imageDownloadFinish() called with: imageLoadDone = [" + imageLoadDone + "]"); 57 | } 58 | }) 59 | .into(textView); 60 | 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /app/src/main/java/zhou/demo/GifActivity.java: -------------------------------------------------------------------------------- 1 | package zhou.demo; 2 | 3 | import android.os.Bundle; 4 | import androidx.annotation.Nullable; 5 | import androidx.appcompat.app.AppCompatActivity; 6 | import android.view.View; 7 | import android.widget.TextView; 8 | 9 | import com.zzhoujay.richtext.RichText; 10 | 11 | /** 12 | * Created by zhou on 16-6-19. 13 | */ 14 | public class GifActivity extends AppCompatActivity { 15 | 16 | private static final String GIF_TEST = "

Gif Test

" + 17 | "

Test2

"; 18 | private static final String GIF_TEST1 = "'

蒋劲夫,黑人劲爆扣篮,潘玮柏犀利突破,娱乐圈男星谁篮球水平高

体育热评 2017-03-17 21:53

“黑人”陈建州,16岁就代表中华台北参加“亚洲青年锦标赛”,21岁就成为了职业篮球运动员,身体素质就不用说了,身高189cm,体重90kg,职业球员的身体条件,娱乐圈估计也很难找出第二个了。

\\\"192000023d95200c4479.gif\\\"/

随便虐篮筐,这力量,爆发力都很足啊。

\\\"192000023da900931bcd.gif\\\"/

潘玮柏,这是他高中时期比赛的画面,滞空能力非常出色,而且据说潘玮柏获得了NCAA的奖学金,是有机会,有能力打NCAA联赛的。

\\\"191e00024266fa8e3f5c.gif\\\"/

\\\"191c000243cf27494877.gif\\\"/

身体很灵活,很像NBA马刺队的托尼-帕克有没有?

\\\"191f00029aba6488b6a0.gif\\\"/

霍建华,文质彬彬的,没想到篮球打得也很厉害吗,急停跳投也是可以的。

\\\"191400048a4b4277b9f3.gif\\\"/

连续交叉胯下,这基本功也很扎实啊。

\\\"191c0002a9fe59c5afba.gif\\\"/

蒋劲夫,可以称得上是娱乐圈的飞人了,也被称为打球最好的男星之一,这双手扣篮也很劲爆啊,弹跳非常出色。

\\\"191c0002abb1d0028c71.gif\\\"/

单臂灌篮,一个被演艺事业耽误了的篮球少年的。

\\\"19190002a33d671fc6b2.gif\\\"/

作为一个非职业的选手,这投篮能力也不错了,能投,能突,能扣,这水平打野球,称霸野球赛场应该没有任何压力吧。

\\\"191e0002ab1644a67801.gif\\\"/


'"; 19 | TextView textView; 20 | 21 | @Override 22 | protected void onCreate(@Nullable Bundle savedInstanceState) { 23 | super.onCreate(savedInstanceState); 24 | setContentView(R.layout.activity_main); 25 | 26 | textView = (TextView) findViewById(R.id.text); 27 | textView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); 28 | RichText.from(GIF_TEST).autoFix(false).showBorder(true).autoPlay(true).into(textView); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /app/src/main/java/zhou/demo/ListViewActivity.java: -------------------------------------------------------------------------------- 1 | package zhou.demo; 2 | 3 | import android.os.Bundle; 4 | import androidx.annotation.Nullable; 5 | import androidx.appcompat.app.AppCompatActivity; 6 | import android.util.Log; 7 | import android.view.LayoutInflater; 8 | import android.view.View; 9 | import android.view.ViewGroup; 10 | import android.widget.BaseAdapter; 11 | import android.widget.ListView; 12 | import android.widget.TextView; 13 | 14 | import com.zzhoujay.richtext.ImageHolder; 15 | import com.zzhoujay.richtext.RichText; 16 | import com.zzhoujay.richtext.callback.SimpleImageFixCallback; 17 | 18 | /** 19 | * Created by zhou on 16-6-17. 20 | */ 21 | public class ListViewActivity extends AppCompatActivity { 22 | 23 | // private static final String[] testString = new String[]{ 24 | // "

Test1

", 25 | // "

Test2

", 26 | // "

Test3

", 27 | // "

Test4

", 28 | // "

Test5

", 29 | // "

Test6

", 30 | // "

Test7

", 31 | // "

Test8

", 32 | // "

Test9

" 33 | // }; 34 | 35 | private static final String gifTest = "

Gif Test

"; 36 | 37 | private static final String[] testString = { 38 | "

Test1

", 39 | "

Test2

", 40 | "

Test3

", 41 | "

Test4

", 42 | "

Test5

", 43 | "

Test6

", 44 | "

Test7

", 45 | "

Test8

", 46 | "

Test9

" 47 | }; 48 | private static final String[] testString__ = { 49 | "

Test1

", 50 | "

Test2

", 51 | "

Test9

", 52 | "

Test3

", 53 | "

Test4

", 54 | "

Test5

", 55 | "

Test6

", 56 | // "

Test7

", 57 | // "

Test8

", 58 | // "

Test9

" 59 | }; 60 | 61 | 62 | @Override 63 | protected void onCreate(@Nullable Bundle savedInstanceState) { 64 | super.onCreate(savedInstanceState); 65 | setContentView(R.layout.activity_list); 66 | 67 | ListView listView = (ListView) findViewById(R.id.listView); 68 | listView.setAdapter(new BaseAdapter() { 69 | @Override 70 | public int getCount() { 71 | return testString__.length + 1; 72 | } 73 | 74 | @Override 75 | public Object getItem(int position) { 76 | return testString[position]; 77 | } 78 | 79 | @Override 80 | public long getItemId(int position) { 81 | return position; 82 | } 83 | 84 | @Override 85 | public View getView(final int position, View convertView, ViewGroup parent) { 86 | Holder holder; 87 | if (convertView == null) { 88 | convertView = LayoutInflater.from(ListViewActivity.this).inflate(R.layout.item_list, parent, false); 89 | holder = new Holder(convertView); 90 | convertView.setTag(holder); 91 | } else { 92 | holder = (Holder) convertView.getTag(); 93 | } 94 | Log.i("RichText", "position:" + position + ",textView:" + System.identityHashCode(holder.text)); 95 | String text; 96 | if (position == 0) { 97 | text = gifTest; 98 | } else { 99 | text = testString__[position - 1]; 100 | } 101 | RichText.from(text).autoPlay(true).singleLoad(false).fix(new SimpleImageFixCallback() { 102 | @Override 103 | public void onInit(ImageHolder holder) { 104 | if (holder.isGif()) { 105 | holder.setAutoFix(false); 106 | } 107 | } 108 | }).into(holder.text); 109 | return convertView; 110 | } 111 | 112 | class Holder { 113 | public final TextView text; 114 | 115 | public Holder(View view) { 116 | text = (TextView) view.findViewById(R.id.text_item); 117 | } 118 | } 119 | }); 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /app/src/main/java/zhou/demo/RecyclerViewActivity.java: -------------------------------------------------------------------------------- 1 | package zhou.demo; 2 | 3 | import android.os.Bundle; 4 | import androidx.annotation.Nullable; 5 | import androidx.appcompat.app.AppCompatActivity; 6 | import androidx.recyclerview.widget.LinearLayoutManager; 7 | import androidx.recyclerview.widget.RecyclerView; 8 | import android.view.LayoutInflater; 9 | import android.view.View; 10 | import android.view.ViewGroup; 11 | import android.widget.TextView; 12 | 13 | import com.zzhoujay.richtext.RichText; 14 | 15 | /** 16 | * Created by zhou on 16-6-17. 17 | */ 18 | public class RecyclerViewActivity extends AppCompatActivity { 19 | 20 | private static final String[] testString1 = new String[]{ 21 | "

Test1

", 22 | "

Test2

", 23 | "

Test3

", 24 | "

Test4

", 25 | "

Test5

", 26 | "

Test6

", 27 | "

Test7

", 28 | "

Test8

", 29 | "

Test9

", 30 | }; 31 | // private static final String[] testString1 = new String[]{ 32 | // "

Test1

hello

", 33 | // "

Test2

hello

", 34 | // "

Test3

hello

", 35 | // "

Test4

hello

", 36 | // "

Test5

hello

", 37 | // "

Test6

hello

", 38 | // "

Test7

hello

", 39 | // "

Test8

hello

", 40 | // "

Test9

hello

", 41 | // }; 42 | 43 | private static final String[] testStringImage = { 44 | "http://www.aikf.com/ask/resources/images/facialExpression/qq/1.gif", 45 | "http://www.aikf.com/ask/resources/images/facialExpression/qq/2.gif", 46 | "http://www.aikf.com/ask/resources/images/facialExpression/qq/3.gif", 47 | "http://www.aikf.com/ask/resources/images/facialExpression/qq/4.gif", 48 | "http://www.aikf.com/ask/resources/images/facialExpression/qq/5.gif", 49 | "http://www.aikf.com/ask/resources/images/facialExpression/qq/6.gif", 50 | "http://www.aikf.com/ask/resources/images/facialExpression/qq/7.gif", 51 | "http://www.aikf.com/ask/resources/images/facialExpression/qq/8.gif", 52 | "http://www.aikf.com/ask/resources/images/facialExpression/qq/9.gif", 53 | }; 54 | 55 | private static final String[] testString = { 56 | "

Test1

", 57 | "

Test2

", 58 | "

Test3

", 59 | "

Test4

", 60 | "

Test5

", 61 | "

Test6

", 62 | "

Test7

", 63 | "

Test8

", 64 | "

Test9

", 65 | 66 | 67 | }; 68 | 69 | 70 | @Override 71 | protected void onCreate(@Nullable Bundle savedInstanceState) { 72 | super.onCreate(savedInstanceState); 73 | setContentView(R.layout.activity_recycler); 74 | 75 | RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView); 76 | recyclerView.setLayoutManager(new LinearLayoutManager(this)); 77 | recyclerView.setAdapter(new RecyclerView.Adapter() { 78 | @Override 79 | public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 80 | return new Holder(LayoutInflater.from(RecyclerViewActivity.this).inflate(R.layout.item_list, parent, false)); 81 | } 82 | 83 | @Override 84 | public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { 85 | if (holder instanceof Holder) { 86 | Holder h = (Holder) holder; 87 | RichText.from(testString1[position]).singleLoad(false).into(h.text); 88 | } 89 | } 90 | 91 | @Override 92 | public int getItemCount() { 93 | return testString1.length; 94 | } 95 | 96 | class Holder extends RecyclerView.ViewHolder { 97 | 98 | public TextView text; 99 | public TextView id; 100 | 101 | public Holder(View itemView) { 102 | super(itemView); 103 | text = (TextView) itemView.findViewById(R.id.text_item); 104 | // id = (TextView) itemView.findViewById(R.id.text_id); 105 | } 106 | } 107 | }); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /app/src/main/java/zhou/demo/TestActivity.java: -------------------------------------------------------------------------------- 1 | package zhou.demo; 2 | 3 | import android.os.Bundle; 4 | import androidx.annotation.Nullable; 5 | import androidx.appcompat.app.AppCompatActivity; 6 | import android.widget.TextView; 7 | import android.widget.Toast; 8 | 9 | import com.zzhoujay.richtext.RichText; 10 | import com.zzhoujay.richtext.callback.OnImageClickListener; 11 | 12 | import java.util.Calendar; 13 | import java.util.List; 14 | 15 | /** 16 | * Created by zhou on 16-10-22. 17 | */ 18 | 19 | public class TestActivity extends AppCompatActivity { 20 | 21 | static final String test = "

Test

" + 22 | "\"\"" + 23 | "\"\"" + 24 | "\"\"" + 25 | "\"\"" + 26 | "\"\"" + 27 | "\"\"" + 28 | "\"\"" + 29 | "
" + 30 | "
"; 31 | 32 | private RichText richText; 33 | private TextView textView; 34 | 35 | @Override 36 | protected void onCreate(@Nullable Bundle savedInstanceState) { 37 | super.onCreate(savedInstanceState); 38 | setContentView(R.layout.activity_test); 39 | 40 | textView = findViewById(R.id.text); 41 | 42 | assert textView != null; 43 | 44 | richText = RichText.from(test) 45 | .imageClick(new OnImageClickListener() { 46 | @Override 47 | public void imageClicked(List imageUrls, int position) { 48 | Calendar calendar = Calendar.getInstance(); 49 | int m = calendar.get(Calendar.MINUTE); 50 | int s = calendar.get(Calendar.SECOND); 51 | Toast.makeText(TestActivity.this, "M:" + m + ",S:" + s, Toast.LENGTH_SHORT).show(); 52 | } 53 | }).into(textView); 54 | 55 | } 56 | 57 | @Override 58 | protected void onDestroy() { 59 | super.onDestroy(); 60 | richText.clear(); 61 | richText = null; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/sl.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/L-X-J/RichText-Androidx/e81cb12ecc3a14047b0c54fe79b1e10fee41b646/app/src/main/res/drawable/sl.jpg -------------------------------------------------------------------------------- /app/src/main/res/drawable/test.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_debug.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 11 | 12 | 16 | 17 | 21 | 22 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_list.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 12 | 13 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 15 | 16 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_recycler.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_test.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 11 | 12 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /app/src/main/res/layout/item_list.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 13 | 14 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/L-X-J/RichText-Androidx/e81cb12ecc3a14047b0c54fe79b1e10fee41b646/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/L-X-J/RichText-Androidx/e81cb12ecc3a14047b0c54fe79b1e10fee41b646/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/L-X-J/RichText-Androidx/e81cb12ecc3a14047b0c54fe79b1e10fee41b646/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/L-X-J/RichText-Androidx/e81cb12ecc3a14047b0c54fe79b1e10fee41b646/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/L-X-J/RichText-Androidx/e81cb12ecc3a14047b0c54fe79b1e10fee41b646/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/raw/hello.md: -------------------------------------------------------------------------------- 1 | # RichText 2 | 3 | > Android平台下的富文本解析器 4 | 5 | * 流式操作 6 | * 低侵入性 7 | * 支持Html格式文本 8 | * 支持图片点击事件 9 | * 链接自动回调 10 | * 支持设置加载中和加载错误时的图片 11 | * 支持自定义超链接的点击回调 12 | * 支持修正图片宽高 13 | * 支持GIF图片 14 | 15 | ### 效果 16 | 17 | ![演示](https://raw.githubusercontent.com/zzhoujay/RichText/master/image/image.jpg "演示") 18 | 19 | 20 | ### gradle中引用的方法 21 | 22 | ``` 23 | implementation 'com.zzhoujay.richtext:richtext:1.1.5' 24 | ``` 25 | 26 | --- 27 | 28 | ### 使用方式 29 | 30 | ``` 31 | RichText.from(text).into(textView); 32 | ``` 33 | 34 | 高级 35 | 36 | ``` 37 | RichText 38 | .from(text) // 数据源 39 | .autoFix(true) // 是否自动修复,默认true 40 | .async(true) // 是否异步,默认false 41 | .fix(imageFixCallback) // 设置自定义修复图片宽高 42 | .imageClick(onImageClickListener) // 设置图片点击回调 43 | .urlClick(onURLClickListener) // 设置链接点击回调 44 | .placeHolder(placeHolder) // 设置加载中显示的占位图 45 | .error(errorImage) // 设置加载失败的错误图 46 | .into(textView); // 设置目标TextView 47 | ``` 48 | 49 | ### 自定义修复宽高 50 | `hello` 51 | ``` 52 | RichText.from(text).fix(new ImageFixCallback() { 53 | @Override 54 | public void onFix(ImageHolder holder,boolean imageReady) { 55 | if(imageReady){ 56 | return; 57 | } 58 | if(holder.getImageType()==ImageHolder.GIF){ 59 | holder.setWidth(400); 60 | holder.setHeight(400); 61 | }else { 62 | holder.setAutoFix(true); 63 | } 64 | } 65 | }) 66 | ``` 67 | 68 | 通过设置`holder.setAutoFix(true)`设置该图片为自动修复,自动修复的效果是图片按宽度充满,所有如果有些小的图片设置了自动填充可能会 69 | 失真,这时候可以取消自动修复设置自定义修复,将比较小的图片过滤出来,将其它的图片自动修复即可。 70 | 71 | 注意,如果img标签中没有宽高的话onFix方法会在图片加载完成前后调用两次,可以通过imageReady来判断 72 | 73 | 如下: 74 | ``` 75 | RichText.from(text).autoFix(false).fix(new ImageFixCallback() { 76 | @Override 77 | public void onFix(ImageHolder holder, boolean imageReady) { 78 | if (holder.getWidth() > 500 && holder.getHeight() > 500) { 79 | holder.setAutoFix(true); 80 | } 81 | } 82 | }).into(textView); 83 | ``` 84 | 85 | ### 注意 86 | 87 | * gif图片播放在API12以下需要手动调用recycler,不然直到应用退出gif图片都会一直刷新 88 | * 目前只能自动通过src的后缀识别是否为gif图,可以通过设置ImageFixCallback对某个特点的图片设置为GIF 89 | ,例如:`holder.setImageType(ImageHolder.GIF)` 90 | * 只支持Html.fromHtml能够解析的标签,自定义标签的支持后续会跟上的 91 | 92 | ### 后续计划 93 | 94 | * 添加自定义标签的支持 95 | * 添加MarkDown语法的支持 96 | 97 | ### 具体使用请查看demo 98 | 99 | [ListView Demo](https://github.com/zzhoujay/RichText/blob/master/app/src/main/java/zhou/demo/ListViewActivity.java)、 100 | [RecyclerView Demo](https://github.com/zzhoujay/RichText/blob/master/app/src/main/java/zhou/demo/RecyclerViewActivity.java)、 101 | [Gif Demo](https://github.com/zzhoujay/RichText/blob/master/app/src/main/java/zhou/demo/GifActivity.java) 102 | 103 | _by zzhoujay_ -------------------------------------------------------------------------------- /app/src/main/res/raw/large: -------------------------------------------------------------------------------- 1 |
2 | 汉仪喵魂体!
3 | 自己写了小半年的手写字体刚上线,自我感觉还是值得推荐的!
4 | 我先给大家图文并茂地讲讲这字儿怎么值得推荐!
5 | 8 | 9 | 12 | 13 | 16 | 17 | 20 | 21 | 24 |
25 | 字库加标点接近一万字
26 |
我的极速是除了吃饭睡觉
27 | 一刻不停的写
一天最多300字
28 | 极速一天之后第二天就要最少崩溃半天
29 | 哈哈哈哈哈
30 |
上半年因为出书有点拖延
31 |
到临交稿的两个月剩的有点多
32 | 我只好回老家闭关写
33 | (有人做饭啊没有干扰还)
34 | 有一个半月的时间里
35 | 每天都
36 | 从天亮写到天黑
37 | 从睁眼写到闭眼
38 |
微信朋友圈还合作什么的
39 | 啥也不管了不回了
40 |
特别的酸爽
41 | 坚持下来之后感觉耐力提升了一百倍
42 |
之后谁再说什么事儿忍不了抛不下
43 | 我就特别想说
44 | 你去抛下一切功名利禄社交合作
45 | 写俩月字库试试
之后什么矫情都没了
46 |
云淡风轻的
47 | 50 | 51 | 54 | 55 | 啊……
56 | 最近又有一个字体的想法……
57 | 还蛮好看……
58 | 但是写一套太累辣!
59 |
粉丝的话可以加我私人微信号:catsoulmini
60 | (同行或职业达人之类加了备注一下身份即可) 61 |
-------------------------------------------------------------------------------- /app/src/main/res/raw/sl.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/L-X-J/RichText-Androidx/e81cb12ecc3a14047b0c54fe79b1e10fee41b646/app/src/main/res/raw/sl.jpg -------------------------------------------------------------------------------- /app/src/main/res/raw/tt.md: -------------------------------------------------------------------------------- 1 | # MarkDown 2 | 3 | > Android平台的原生Markdown解析器,已整合进 [RichText](https://github.com/zzhoujay/RichText) 4 | 5 | * 由markdown文本直接转换为Spanned,快捷高效 6 | * 不依赖特定控件,低侵入性 7 | * 遵循 Github Flavored Markdown 标准 8 | 9 | ### 使用 10 | 11 | ``` 12 | Markdown.fromMarkdown(text,imageGetter,textView); 13 | ``` 14 | **注意:** 此方法需要在textView的Measure完成后调用,因为需要获取textView的宽高 15 | 16 | 例子: 17 | ``` 18 | textView.post(new Runnable() { 19 | @Override 20 | public void run() { 21 | Spanned spanned = MarkDown.fromMarkdown(stream, new Html.ImageGetter() { 22 | @Override 23 | public Drawable getDrawable(String source) { 24 | Drawable drawable = getResources().getDrawable(R.mipmap.ic_launcher); 25 | drawable.setBounds(0, 0, 400, 400); 26 | return drawable; 27 | } 28 | }, textView); 29 | textView.setText(spanned); 30 | } 31 | ``` 32 | 33 | ### 在RichText中使用 34 | 35 | [RichText](https://github.com/zzhoujay/RichText) 包含了一些对图片和其它东西的处理,使用更简单 36 | ``` 37 | RichText.fromMarkdown(markdown).into(textView); 38 | ``` 39 | 40 | ### Use in Gradle 41 | 42 | `implementation 'com.zzhoujay.markdown:markdown:0.0.4'` 43 | 44 | 45 | ### 已知问题 46 | 47 | * ~~引用块内不支持Setext-style的标题(后续会想办法修复~~ (已修复) 48 | * 暂不支持使用反斜杠 \\ 转义 49 | * 不支持表格 50 | 51 | 52 | ### 后续计划 53 | 54 | * 修复一些已知问题 55 | 56 | _by zzhoujay_ 57 | -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | RichTextDemo 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/main/res/xml/network_security_config.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ww4.sinaimg.cn 5 | baidu.com 6 | 7 | 8 | -------------------------------------------------------------------------------- /app/src/test/java/zhou/demo/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package zhou.demo; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * To work on unit tests, switch the Test Artifact in the Build Variants view. 9 | */ 10 | public class ExampleUnitTest { 11 | @Test 12 | public void addition_isCorrect() throws Exception { 13 | assertEquals(4, 2 + 2); 14 | } 15 | } -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | mavenCentral() 6 | google() 7 | } 8 | dependencies { 9 | classpath 'com.android.tools.build:gradle:7.2.2' 10 | } 11 | } 12 | 13 | allprojects { 14 | repositories { 15 | maven { url 'https://maven.aliyun.com/repository/public' } 16 | maven { url 'https://maven.aliyun.com/repository/central' } 17 | maven { url 'https://maven.aliyun.com/repository/jcenter' } 18 | mavenCentral() 19 | google() 20 | } 21 | } 22 | 23 | tasks.register('clean', Delete) { 24 | delete rootProject.buildDir 25 | } 26 | -------------------------------------------------------------------------------- /glideimagegetter/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | publish.sh 3 | -------------------------------------------------------------------------------- /glideimagegetter/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'com.novoda.bintray-release' 3 | 4 | def version_code = 6 5 | def version_name = "1.0.5" 6 | 7 | android { 8 | compileSdkVersion 33 9 | 10 | defaultConfig { 11 | minSdkVersion 15 12 | targetSdkVersion 33 13 | versionCode version_code 14 | versionName version_name 15 | 16 | resourcePrefix "zhou_glide_" 17 | 18 | 19 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 20 | 21 | } 22 | buildTypes { 23 | release { 24 | minifyEnabled false 25 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 26 | } 27 | } 28 | lintOptions { 29 | abortOnError false 30 | } 31 | } 32 | 33 | dependencies { 34 | implementation fileTree(include: ['*.jar'], dir: 'libs') 35 | testImplementation 'junit:junit:4.13.2' 36 | implementation 'com.github.bumptech.glide:glide:3.7.0' 37 | implementation 'com.zzhoujay.richtext:richtext:3.0.8' 38 | // implementation project(':richtext') 39 | } 40 | 41 | publish { 42 | 43 | Properties properties = new Properties() 44 | properties.load(project.rootProject.file('local.properties').newDataInputStream()) 45 | //bintray.com用户名 46 | userOrg = properties.getProperty("bintray.user") 47 | //jcenter上的路径 48 | groupId = "com.zzhoujay.glideimagegetter" 49 | //项目名称 50 | artifactId = 'glideimagegetter' 51 | //版本号 52 | publishVersion = version_name 53 | //描述,不重要 54 | desc = 'RichText的Glide图片加载库的插件' 55 | //网站,不重要 56 | website = 'https://github.com/zzhoujay/RichTex' 57 | 58 | bintrayUser = properties.getProperty("bintray.user") 59 | bintrayKey = properties.getProperty("bintray.apikey") 60 | 61 | } 62 | -------------------------------------------------------------------------------- /glideimagegetter/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/zhou/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /glideimagegetter/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /glideimagegetter/src/main/java/com/zzhoujay/glideimagegetter/GlideImageGetter.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.glideimagegetter; 2 | 3 | import android.graphics.Rect; 4 | import android.graphics.drawable.Drawable; 5 | import androidx.collection.LruCache; 6 | import android.widget.TextView; 7 | 8 | import com.bumptech.glide.BitmapTypeRequest; 9 | import com.bumptech.glide.DrawableTypeRequest; 10 | import com.bumptech.glide.GenericRequestBuilder; 11 | import com.bumptech.glide.GifTypeRequest; 12 | import com.bumptech.glide.Glide; 13 | import com.zzhoujay.richtext.CacheType; 14 | import com.zzhoujay.richtext.ImageHolder; 15 | import com.zzhoujay.richtext.RichTextConfig; 16 | import com.zzhoujay.richtext.callback.ImageGetter; 17 | import com.zzhoujay.richtext.callback.ImageLoadNotify; 18 | import com.zzhoujay.richtext.drawable.DrawableWrapper; 19 | import com.zzhoujay.richtext.ext.Base64; 20 | 21 | import java.util.HashSet; 22 | 23 | /** 24 | * Created by zhou on 2016/12/3. 25 | * 使用Glide作为图片加载器 26 | *

27 | * 不在建议使用,建议使用DefaultImageGetter基本可以替代此类。 28 | * 此类后面将不会维护了,请尽快转移! 29 | */ 30 | @Deprecated 31 | public class GlideImageGetter implements ImageGetter, ImageLoadNotify { 32 | 33 | private static final int TARGET_TAG = R.id.zhou_glide_image_tag_id; 34 | 35 | private static final LruCache imageBoundCache; 36 | 37 | static { 38 | imageBoundCache = new LruCache<>(20); 39 | } 40 | 41 | private static void cache(String source, Rect rect) { 42 | imageBoundCache.put(source, rect); 43 | } 44 | 45 | private static Rect loadCache(String source) { 46 | return imageBoundCache.get(source); 47 | } 48 | 49 | private HashSet targets; 50 | private ImageLoadNotify imageLoadNotify; 51 | private int loadedCount; 52 | 53 | public GlideImageGetter() { 54 | targets = new HashSet<>(); 55 | } 56 | 57 | private void checkTag(TextView textView) { 58 | //noinspection unchecked 59 | HashSet ts = (HashSet) textView.getTag(TARGET_TAG); 60 | if (ts != null) { 61 | if (ts == targets) { 62 | return; 63 | } 64 | for (ImageTarget target : ts) { 65 | target.recycle(); 66 | } 67 | ts.clear(); 68 | } 69 | textView.setTag(TARGET_TAG, targets); 70 | } 71 | 72 | @Override 73 | public Drawable getDrawable(ImageHolder holder, final RichTextConfig config, TextView textView) { 74 | final ImageTarget target; 75 | final GenericRequestBuilder load; 76 | DrawableTypeRequest dtr; 77 | DrawableWrapper drawableWrapper = new DrawableWrapper(); 78 | byte[] src = Base64.decode(holder.getSource()); 79 | if (src != null) { 80 | dtr = Glide.with(textView.getContext()).load(src); 81 | } else { 82 | dtr = Glide.with(textView.getContext()).load(holder.getSource()); 83 | } 84 | Rect rect = null; 85 | if (config.cacheType >= CacheType.LAYOUT) { 86 | rect = loadCache(holder.getSource()); 87 | if (rect != null) { 88 | drawableWrapper.setBounds(rect); 89 | } 90 | } else { 91 | drawableWrapper.setBounds(0, 0, holder.getWidth(), holder.getHeight()); 92 | } 93 | if (holder.isGif()) { 94 | target = new ImageTargetGif(textView, drawableWrapper, holder, config, this, rect); 95 | load = dtr.asGif(); 96 | } else { 97 | target = new ImageTargetBitmap(textView, drawableWrapper, holder, config, this, rect); 98 | load = dtr.asBitmap().atMost(); 99 | } 100 | checkTag(textView); 101 | targets.add(target); 102 | if (!config.resetSize && holder.isInvalidateSize()) { 103 | load.override(holder.getWidth(), holder.getHeight()); 104 | } 105 | if (holder.getScaleType() == ImageHolder.ScaleType.CENTER_CROP) { 106 | if (holder.isGif()) { 107 | //noinspection ConstantConditions 108 | ((GifTypeRequest) load).centerCrop(); 109 | } else { 110 | //noinspection ConstantConditions 111 | ((BitmapTypeRequest) load).centerCrop(); 112 | } 113 | } else if (holder.getScaleType() == ImageHolder.ScaleType.FIT_CENTER) { 114 | if (holder.isGif()) { 115 | //noinspection ConstantConditions 116 | ((GifTypeRequest) load).fitCenter(); 117 | } else { 118 | //noinspection ConstantConditions 119 | ((BitmapTypeRequest) load).fitCenter(); 120 | } 121 | } 122 | textView.post(new Runnable() { 123 | @Override 124 | public void run() { 125 | load.placeholder(config.placeHolder).error(config.errorImage).into(target); 126 | } 127 | }); 128 | drawableWrapper.setCallback(textView); 129 | return drawableWrapper; 130 | } 131 | 132 | @Override 133 | public void registerImageLoadNotify(ImageLoadNotify imageLoadNotify) { 134 | this.imageLoadNotify = imageLoadNotify; 135 | } 136 | 137 | @Override 138 | public void done(Object from) { 139 | if (from instanceof ImageTarget) { 140 | ImageTarget imageTarget = (ImageTarget) from; 141 | DrawableWrapper drawableWrapper = (DrawableWrapper) imageTarget.urlDrawableWeakReference.get(); 142 | if (drawableWrapper != null && imageTarget.config.cacheType >= CacheType.LAYOUT) { 143 | cache(imageTarget.holder.getSource(), drawableWrapper.getBounds()); 144 | } 145 | targets.remove(imageTarget); 146 | loadedCount++; 147 | if (imageLoadNotify != null) { 148 | imageLoadNotify.done(loadedCount); 149 | } 150 | } 151 | } 152 | 153 | @Override 154 | public void recycle() { 155 | for (ImageTarget target : targets) { 156 | target.recycle(); 157 | } 158 | targets.clear(); 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /glideimagegetter/src/main/java/com/zzhoujay/glideimagegetter/ImageTarget.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.glideimagegetter; 2 | 3 | import android.app.Activity; 4 | import android.content.Context; 5 | import android.graphics.Rect; 6 | import android.graphics.drawable.Drawable; 7 | import android.os.Build; 8 | import androidx.appcompat.widget.TintContextWrapper; 9 | import android.widget.TextView; 10 | 11 | import com.bumptech.glide.request.target.BaseTarget; 12 | import com.bumptech.glide.request.target.SizeReadyCallback; 13 | import com.zzhoujay.richtext.ImageHolder; 14 | import com.zzhoujay.richtext.RichTextConfig; 15 | import com.zzhoujay.richtext.callback.ImageLoadNotify; 16 | import com.zzhoujay.richtext.callback.Recyclable; 17 | import com.zzhoujay.richtext.drawable.DrawableWrapper; 18 | 19 | import java.lang.ref.WeakReference; 20 | 21 | /** 22 | * Created by zhou on 16-10-23. 23 | * Image target 24 | */ 25 | abstract class ImageTarget extends BaseTarget implements Recyclable { 26 | 27 | final WeakReference textViewWeakReference; 28 | final WeakReference urlDrawableWeakReference; 29 | final ImageHolder holder; 30 | private final WeakReference imageLoadNotifyWeakReference; 31 | final RichTextConfig config; 32 | final Rect rect; 33 | 34 | ImageTarget(TextView textView, DrawableWrapper drawableWrapper, ImageHolder holder, RichTextConfig config, ImageLoadNotify imageLoadNotify, Rect rect) { 35 | this.textViewWeakReference = new WeakReference<>(textView); 36 | this.urlDrawableWeakReference = new WeakReference<>(drawableWrapper); 37 | this.holder = holder; 38 | this.config = config; 39 | this.imageLoadNotifyWeakReference = new WeakReference<>(imageLoadNotify); 40 | this.rect = rect; 41 | } 42 | 43 | @Override 44 | public void onLoadStarted(Drawable placeholder) { 45 | super.onLoadStarted(placeholder); 46 | if (placeholder == null || !activityIsAlive()) { 47 | return; 48 | } 49 | DrawableWrapper drawableWrapper = urlDrawableWeakReference.get(); 50 | if (drawableWrapper == null) { 51 | return; 52 | } 53 | holder.setImageState(ImageHolder.ImageState.LOADING); 54 | drawableWrapper.setDrawable(placeholder); 55 | if (rect != null) { 56 | drawableWrapper.setBounds(rect); 57 | } else { 58 | if (!config.autoFix && config.imageFixCallback != null) { 59 | config.imageFixCallback.onLoading(holder); 60 | } 61 | int width; 62 | int height = 0; 63 | if (config.autoFix || holder.isAutoFix() || !holder.isInvalidateSize()) { 64 | width = getRealWidth(); 65 | int ow = placeholder.getBounds().width(); 66 | if (ow != 0) { 67 | height = placeholder.getBounds().height() * width / ow; 68 | } 69 | if (height == 0) { 70 | height = width / 2; 71 | } 72 | } else { 73 | width = holder.getWidth(); 74 | height = holder.getHeight(); 75 | } 76 | drawableWrapper.setBounds(0, 0, width, height); 77 | } 78 | resetText(); 79 | } 80 | 81 | @Override 82 | public void onLoadFailed(Exception e, Drawable errorDrawable) { 83 | super.onLoadFailed(e, errorDrawable); 84 | if (errorDrawable == null || !activityIsAlive()) { 85 | return; 86 | } 87 | DrawableWrapper drawableWrapper = urlDrawableWeakReference.get(); 88 | if (drawableWrapper == null) { 89 | return; 90 | } 91 | holder.setImageState(ImageHolder.ImageState.FAILED); 92 | drawableWrapper.setDrawable(errorDrawable); 93 | if (rect != null) { 94 | drawableWrapper.setBounds(rect); 95 | } else { 96 | if (!config.autoFix && config.imageFixCallback != null) { 97 | config.imageFixCallback.onFailure(holder, e); 98 | } 99 | int width; 100 | int height = 0; 101 | if (config.autoFix || holder.isAutoFix() || !holder.isInvalidateSize()) { 102 | width = getRealWidth(); 103 | int ow = errorDrawable.getBounds().width(); 104 | if (ow != 0) { 105 | height = errorDrawable.getBounds().height() * width / ow; 106 | } 107 | if (height == 0) { 108 | height = width / 2; 109 | } 110 | } else { 111 | width = holder.getWidth(); 112 | height = holder.getHeight(); 113 | } 114 | drawableWrapper.setBounds(0, 0, width, height); 115 | } 116 | resetText(); 117 | loadDone(); 118 | } 119 | 120 | @Override 121 | public void getSize(SizeReadyCallback cb) { 122 | int maxWidth = getRealWidth(), maxHeight = Integer.MAX_VALUE; 123 | if (config.imageFixCallback != null) { 124 | holder.setImageState(ImageHolder.ImageState.SIZE_READY); 125 | ImageHolder.SizeHolder sizeHolder = new ImageHolder.SizeHolder(0, 0); 126 | config.imageFixCallback.onSizeReady(holder, 0, 0, sizeHolder); 127 | if (sizeHolder.isInvalidateSize()) { 128 | maxWidth = sizeHolder.getWidth(); 129 | maxHeight = sizeHolder.getHeight(); 130 | } 131 | } 132 | cb.onSizeReady(maxWidth, maxHeight); 133 | } 134 | 135 | /** 136 | * 获取可用宽度 137 | * 138 | * @return width 139 | */ 140 | int getRealWidth() { 141 | TextView tv = textViewWeakReference.get(); 142 | if (tv == null) { 143 | return 0; 144 | } 145 | return tv.getWidth() - tv.getPaddingRight() - tv.getPaddingLeft(); 146 | } 147 | 148 | int getReadHeight() { 149 | TextView tv = textViewWeakReference.get(); 150 | if (tv == null) { 151 | return 0; 152 | } 153 | return tv.getHeight() - tv.getPaddingTop() - tv.getPaddingBottom(); 154 | } 155 | 156 | void resetText() { 157 | TextView tv = textViewWeakReference.get(); 158 | if (tv != null) { 159 | CharSequence cs = tv.getText(); 160 | tv.setText(cs); 161 | } 162 | } 163 | 164 | void loadDone() { 165 | ImageLoadNotify notify = imageLoadNotifyWeakReference.get(); 166 | if (notify != null) { 167 | notify.done(this); 168 | } 169 | } 170 | 171 | /** 172 | * 判断Activity是否已经结束 173 | * 174 | * @return true:已结束 175 | */ 176 | boolean activityIsAlive() { 177 | TextView textView = textViewWeakReference.get(); 178 | if (textView == null) { 179 | return false; 180 | } 181 | Context context = textView.getContext(); 182 | if (context == null) { 183 | return false; 184 | } 185 | if (context instanceof TintContextWrapper) { 186 | context = ((TintContextWrapper) context).getBaseContext(); 187 | } 188 | if (context instanceof Activity) { 189 | if (((Activity) context).isFinishing()) { 190 | return false; 191 | } else { 192 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && ((Activity) context).isDestroyed()) { 193 | return false; 194 | } 195 | } 196 | } 197 | return true; 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /glideimagegetter/src/main/java/com/zzhoujay/glideimagegetter/ImageTargetBitmap.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.glideimagegetter; 2 | 3 | import android.graphics.Bitmap; 4 | import android.graphics.Rect; 5 | import android.graphics.drawable.BitmapDrawable; 6 | import android.graphics.drawable.Drawable; 7 | import android.widget.TextView; 8 | 9 | import com.bumptech.glide.Glide; 10 | import com.bumptech.glide.request.animation.GlideAnimation; 11 | import com.zzhoujay.richtext.ImageHolder; 12 | import com.zzhoujay.richtext.RichTextConfig; 13 | import com.zzhoujay.richtext.callback.ImageLoadNotify; 14 | import com.zzhoujay.richtext.drawable.DrawableWrapper; 15 | 16 | /** 17 | * Created by zhou on 16-10-23. 18 | * ImageTarget Bitmap 19 | */ 20 | class ImageTargetBitmap extends ImageTarget { 21 | 22 | 23 | ImageTargetBitmap(TextView textView, DrawableWrapper drawableWrapper, ImageHolder holder, RichTextConfig config, ImageLoadNotify imageLoadNotify, Rect rect) { 24 | super(textView, drawableWrapper, holder, config, imageLoadNotify, rect); 25 | } 26 | 27 | @Override 28 | public void recycle() { 29 | Glide.clear(this); 30 | } 31 | 32 | @Override 33 | public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) { 34 | if (!activityIsAlive()) { 35 | return; 36 | } 37 | DrawableWrapper drawableWrapper = urlDrawableWeakReference.get(); 38 | if (drawableWrapper == null) { 39 | return; 40 | } 41 | TextView textView = textViewWeakReference.get(); 42 | holder.setImageState(ImageHolder.ImageState.READY); 43 | holder.setSize(resource.getWidth(), resource.getHeight()); 44 | Drawable drawable = new BitmapDrawable(textView.getContext().getResources(), resource); 45 | drawableWrapper.setDrawable(drawable); 46 | if (rect != null) { 47 | drawableWrapper.setBounds(rect); 48 | } else { 49 | if (!config.autoFix && config.imageFixCallback != null) { 50 | config.imageFixCallback.onImageReady(holder, resource.getWidth(), resource.getHeight()); 51 | } 52 | if (config.autoFix || holder.isAutoFix() || !holder.isInvalidateSize()) { 53 | int width = getRealWidth(); 54 | int height = (int) ((float) resource.getHeight() * width / resource.getWidth()); 55 | drawableWrapper.setBounds(0, 0, width, height); 56 | } else { 57 | drawableWrapper.setBounds(0, 0, holder.getWidth(), holder.getHeight()); 58 | } 59 | } 60 | resetText(); 61 | loadDone(); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /glideimagegetter/src/main/java/com/zzhoujay/glideimagegetter/ImageTargetGif.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.glideimagegetter; 2 | 3 | import android.graphics.Bitmap; 4 | import android.graphics.Rect; 5 | import android.graphics.drawable.Drawable; 6 | import androidx.annotation.NonNull; 7 | import android.widget.TextView; 8 | 9 | import com.bumptech.glide.Glide; 10 | import com.bumptech.glide.load.resource.drawable.GlideDrawable; 11 | import com.bumptech.glide.load.resource.gif.GifDrawable; 12 | import com.bumptech.glide.request.animation.GlideAnimation; 13 | import com.zzhoujay.richtext.ImageHolder; 14 | import com.zzhoujay.richtext.RichTextConfig; 15 | import com.zzhoujay.richtext.callback.ImageLoadNotify; 16 | import com.zzhoujay.richtext.drawable.DrawableWrapper; 17 | 18 | import java.lang.ref.SoftReference; 19 | 20 | /** 21 | * Created by zhou on 16-10-23. 22 | * ImageTarget Gif 23 | */ 24 | class ImageTargetGif extends ImageTarget implements Drawable.Callback { 25 | 26 | private SoftReference gifDrawableSoftReference; 27 | 28 | ImageTargetGif(TextView textView, DrawableWrapper drawableWrapper, ImageHolder holder, RichTextConfig config, ImageLoadNotify imageLoadNotify, Rect rect) { 29 | super(textView, drawableWrapper, holder, config, imageLoadNotify, rect); 30 | } 31 | 32 | 33 | @Override 34 | public void recycle() { 35 | Glide.clear(this); 36 | if (gifDrawableSoftReference != null) { 37 | GifDrawable gifDrawable = gifDrawableSoftReference.get(); 38 | if (gifDrawable != null) { 39 | gifDrawable.setCallback(null); 40 | gifDrawable.stop(); 41 | } 42 | } 43 | } 44 | 45 | @Override 46 | public void onResourceReady(GifDrawable resource, GlideAnimation glideAnimation) { 47 | if (!activityIsAlive()) { 48 | return; 49 | } 50 | DrawableWrapper drawableWrapper = urlDrawableWeakReference.get(); 51 | if (drawableWrapper == null) { 52 | return; 53 | } 54 | holder.setImageState(ImageHolder.ImageState.READY); 55 | gifDrawableSoftReference = new SoftReference<>(resource); 56 | Bitmap first = resource.getFirstFrame(); 57 | holder.setSize(first.getWidth(), first.getHeight()); 58 | drawableWrapper.setDrawable(resource); 59 | if (rect != null) { 60 | drawableWrapper.setBounds(rect); 61 | } else { 62 | if (!config.autoFix && config.imageFixCallback != null) { 63 | config.imageFixCallback.onImageReady(holder, first.getWidth(), first.getHeight()); 64 | } 65 | if (config.autoFix || holder.isAutoFix() || !holder.isInvalidateSize()) { 66 | int width = getRealWidth(); 67 | int height = (int) ((float) first.getHeight() * width / first.getWidth()); 68 | drawableWrapper.setBounds(0, 0, width, height); 69 | } else { 70 | drawableWrapper.setBounds(0, 0, holder.getWidth(), holder.getHeight()); 71 | } 72 | if (holder.isAutoPlay()) { 73 | resource.setCallback(this); 74 | resource.start(); 75 | resource.setLoopCount(GlideDrawable.LOOP_FOREVER); 76 | } 77 | } 78 | resetText(); 79 | loadDone(); 80 | } 81 | 82 | @Override 83 | public void invalidateDrawable(@NonNull Drawable who) { 84 | TextView textView = textViewWeakReference.get(); 85 | if (textView != null) { 86 | textView.invalidate(); 87 | } else { 88 | recycle(); 89 | } 90 | } 91 | 92 | @Override 93 | public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) { 94 | 95 | } 96 | 97 | @Override 98 | public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) { 99 | 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /glideimagegetter/src/main/res/values/zhou_glide_ids.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /glideimagegetter/src/test/java/com/zzhoujay/glideimagegetter/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.glideimagegetter; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.assertEquals; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() throws Exception { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | android.enableJetifier=true 20 | android.useAndroidX=true -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/L-X-J/RichText-Androidx/e81cb12ecc3a14047b0c54fe79b1e10fee41b646/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Jul 18 17:25:42 CST 2022 2 | distributionBase=GRADLE_USER_HOME 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip 4 | distributionPath=wrapper/dists 5 | zipStorePath=wrapper/dists 6 | zipStoreBase=GRADLE_USER_HOME 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /image/image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/L-X-J/RichText-Androidx/e81cb12ecc3a14047b0c54fe79b1e10fee41b646/image/image.jpg -------------------------------------------------------------------------------- /okhttpimagedownloader/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /okhttpimagedownloader/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 33 5 | 6 | defaultConfig { 7 | minSdkVersion 15 8 | targetSdkVersion 33 9 | 10 | testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' 11 | 12 | } 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 17 | } 18 | } 19 | namespace 'com.zzhoujay.okhttpimagedownloader' 20 | lint { 21 | abortOnError false 22 | } 23 | } 24 | 25 | dependencies { 26 | implementation 'com.squareup.okhttp3:okhttp:3.10.0' 27 | // implementation project(':richtext') 28 | implementation 'com.zzhoujay.richtext:richtext:3.0.8' 29 | } 30 | -------------------------------------------------------------------------------- /okhttpimagedownloader/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/zhou/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | 19 | # Uncomment this to preserve the line number information for 20 | # debugging stack traces. 21 | #-keepattributes SourceFile,LineNumberTable 22 | 23 | # If you keep the line number information, uncomment this to 24 | # hide the original source file name. 25 | #-renamesourcefileattribute SourceFile 26 | -------------------------------------------------------------------------------- /okhttpimagedownloader/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /okhttpimagedownloader/src/main/java/com/zzhoujay/okhttpimagedownloader/OkHttpImageDownloader.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.okhttpimagedownloader; 2 | 3 | import android.annotation.SuppressLint; 4 | 5 | import com.zzhoujay.richtext.callback.BitmapStream; 6 | import com.zzhoujay.richtext.ig.ImageDownloader; 7 | 8 | import java.io.IOException; 9 | import java.io.InputStream; 10 | import java.security.KeyManagementException; 11 | import java.security.NoSuchAlgorithmException; 12 | import java.security.SecureRandom; 13 | import java.security.cert.X509Certificate; 14 | import java.util.concurrent.TimeUnit; 15 | 16 | import javax.net.ssl.HostnameVerifier; 17 | import javax.net.ssl.SSLContext; 18 | import javax.net.ssl.SSLSession; 19 | import javax.net.ssl.TrustManager; 20 | import javax.net.ssl.X509TrustManager; 21 | 22 | import okhttp3.OkHttpClient; 23 | import okhttp3.Request; 24 | import okhttp3.Response; 25 | 26 | /** 27 | * Created by zhou on 2017/9/11. 28 | * 使用OkHttp实现的图片下载器 29 | */ 30 | 31 | @SuppressWarnings("unused") 32 | public class OkHttpImageDownloader implements ImageDownloader { 33 | 34 | @Override 35 | public BitmapStream download(String source) throws IOException { 36 | return new BitmapStreamWrapper(source); 37 | } 38 | 39 | private static class BitmapStreamWrapper implements BitmapStream { 40 | 41 | private final String url; 42 | private Response response; 43 | private InputStream inputStream; 44 | 45 | private BitmapStreamWrapper(String url) { 46 | this.url = url; 47 | } 48 | 49 | @Override 50 | public InputStream getInputStream() throws IOException { 51 | Request request = new Request.Builder().url(url).get().build(); 52 | response = getClient().newCall(request).execute(); 53 | inputStream = response.body().byteStream(); 54 | return inputStream; 55 | } 56 | 57 | @Override 58 | public void close() throws IOException { 59 | if (inputStream != null) { 60 | inputStream.close(); 61 | } 62 | if (response != null) { 63 | response.close(); 64 | } 65 | } 66 | } 67 | 68 | private static OkHttpClient getClient() { 69 | return OkHttpClientHolder.CLIENT; 70 | } 71 | 72 | 73 | private static class OkHttpClientHolder { 74 | private static final OkHttpClient CLIENT; 75 | private static SSLContext sslContext = null; 76 | 77 | private static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { 78 | @SuppressLint("BadHostnameVerifier") 79 | @Override 80 | public boolean verify(String hostname, SSLSession session) { 81 | return true; 82 | } 83 | }; 84 | 85 | static { 86 | // 设置https为全部信任 87 | X509TrustManager xtm = new X509TrustManager() { 88 | @SuppressLint("TrustAllX509TrustManager") 89 | @Override 90 | public void checkClientTrusted(X509Certificate[] chain, String authType) { 91 | } 92 | 93 | @SuppressLint("TrustAllX509TrustManager") 94 | @Override 95 | public void checkServerTrusted(X509Certificate[] chain, String authType) { 96 | } 97 | 98 | @Override 99 | public X509Certificate[] getAcceptedIssuers() { 100 | return new X509Certificate[0]; 101 | } 102 | }; 103 | 104 | 105 | try { 106 | sslContext = SSLContext.getInstance("SSL"); 107 | 108 | sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom()); 109 | 110 | } catch (NoSuchAlgorithmException | KeyManagementException e) { 111 | e.printStackTrace(); 112 | } 113 | 114 | CLIENT = new OkHttpClient().newBuilder() 115 | .readTimeout(10, TimeUnit.SECONDS) 116 | .writeTimeout(10, TimeUnit.SECONDS) 117 | .connectTimeout(10, TimeUnit.SECONDS) 118 | .sslSocketFactory(sslContext.getSocketFactory(), xtm) 119 | .hostnameVerifier(DO_NOT_VERIFY) 120 | .build(); 121 | } 122 | 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /richtext/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | publish.sh -------------------------------------------------------------------------------- /richtext/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | 4 | android { 5 | compileSdk 34 6 | defaultConfig { 7 | minSdkVersion 21 8 | targetSdkVersion 33 9 | } 10 | buildTypes { 11 | release { 12 | minifyEnabled false 13 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 14 | } 15 | } 16 | namespace 'com.zzhoujay.richtext' 17 | lint { 18 | abortOnError false 19 | } 20 | } 21 | 22 | dependencies { 23 | implementation 'com.zzhoujay.markdown:markdown:1.0.5' 24 | implementation 'com.jakewharton:disklrucache:2.0.2' 25 | implementation 'androidx.annotation:annotation:1.8.2' 26 | // implementation 'androidx.legacy:legacy-support-v4:1.0.0' 27 | } -------------------------------------------------------------------------------- /richtext/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /home/zhou/Android/Sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /richtext/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/CacheType.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext; 2 | 3 | /** 4 | * Created by zhou on 2016/12/5. 5 | * CacheType 6 | */ 7 | //@IntDef({CacheType.NONE, CacheType.LAYOUT, CacheType.ALL}) 8 | public enum CacheType { 9 | none(0), layout(1), all(2); 10 | 11 | int value; 12 | 13 | CacheType(int value) { 14 | this.value = value; 15 | } 16 | 17 | public int intValue() { 18 | return value; 19 | } 20 | // int NONE = 0; // 不进行缓存 21 | // int LAYOUT = 1; // 只缓存文字样式和图片大小信息 22 | // int ALL = 2; // 在LAYOUT的基础上还缓存图片,使用前需先设置缓存目录 23 | } 24 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/LinkHolder.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext; 2 | 3 | import android.graphics.Color; 4 | import androidx.annotation.ColorInt; 5 | 6 | /** 7 | * Created by zhou on 2016/11/17. 8 | * LinkHolder 9 | */ 10 | @SuppressWarnings("unused") 11 | public class LinkHolder { 12 | 13 | private static final int link_color = Color.parseColor("#4078C0"); 14 | 15 | private final String url; 16 | @ColorInt 17 | private int color; 18 | private boolean underLine; 19 | 20 | public LinkHolder(String url) { 21 | this.url = url; 22 | this.color = link_color; 23 | underLine = true; 24 | } 25 | 26 | @ColorInt 27 | public int getColor() { 28 | return color; 29 | } 30 | 31 | public void setColor(@ColorInt int color) { 32 | this.color = color; 33 | } 34 | 35 | public boolean isUnderLine() { 36 | return underLine; 37 | } 38 | 39 | public void setUnderLine(boolean underLine) { 40 | this.underLine = underLine; 41 | } 42 | 43 | public String getUrl() { 44 | return url; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/RichState.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext; 2 | 3 | /** 4 | * Created by zhou on 16-10-24. 5 | * Image Load State 6 | */ 7 | public enum RichState { 8 | ready, loading, loaded 9 | } 10 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/RichTextPool.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext; 2 | 3 | import android.text.SpannableStringBuilder; 4 | import android.text.Spanned; 5 | import android.util.LruCache; 6 | 7 | import com.zzhoujay.richtext.ext.Debug; 8 | import com.zzhoujay.richtext.ext.MD5; 9 | import com.zzhoujay.richtext.parser.CachedSpannedParser; 10 | import com.zzhoujay.richtext.spans.ClickableImageSpan; 11 | import com.zzhoujay.richtext.spans.LongClickableURLSpan; 12 | 13 | import java.lang.ref.SoftReference; 14 | import java.lang.ref.WeakReference; 15 | import java.util.HashSet; 16 | import java.util.WeakHashMap; 17 | 18 | /** 19 | * Created by zhou on 2017/3/25. 20 | * RichTextPool 21 | */ 22 | 23 | @SuppressWarnings("WeakerAccess") 24 | class RichTextPool { 25 | 26 | private static final String TAG = "RichTextPool"; 27 | 28 | private static final int MAX_RICH_TEXT_SIZE = 50; 29 | 30 | private final LruCache> richCache; 31 | private final WeakHashMap>> instances; 32 | 33 | 34 | private RichTextPool() { 35 | richCache = new LruCache<>(MAX_RICH_TEXT_SIZE); 36 | instances = new WeakHashMap<>(); 37 | } 38 | 39 | void cache(String source, SpannableStringBuilder ssb) { 40 | String key = MD5.generate(source); 41 | if (richCache.get(key) != null) { 42 | Debug.log(TAG, "cached"); 43 | return; 44 | } 45 | ssb = clearSpans(new SpannableStringBuilder(ssb)); 46 | ssb.setSpan(new CachedSpannedParser.Cached(), 0, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 47 | richCache.put(key, new SoftReference<>(ssb)); 48 | } 49 | 50 | SpannableStringBuilder loadCache(String source) { 51 | SoftReference cache = richCache.get(MD5.generate(source)); 52 | SpannableStringBuilder ssb = cache == null ? null : cache.get(); 53 | if (ssb != null) { 54 | Debug.log(TAG, "cache hit -- text"); 55 | return new SpannableStringBuilder(ssb); 56 | } 57 | return null; 58 | } 59 | 60 | SpannableStringBuilder clearSpans(SpannableStringBuilder ssb) { 61 | ClickableImageSpan[] spans = ssb.getSpans(0, ssb.length(), ClickableImageSpan.class); 62 | if (spans != null && spans.length > 0) { 63 | for (ClickableImageSpan span : spans) { 64 | int start = ssb.getSpanStart(span); 65 | int end = ssb.getSpanEnd(span); 66 | int flags = ssb.getSpanFlags(span); 67 | ClickableImageSpan copy = span.copy(); 68 | ssb.removeSpan(span); 69 | ssb.setSpan(copy, start, end, flags); 70 | } 71 | Debug.loge(TAG, "clearSpans > " + spans.length); 72 | } 73 | 74 | LongClickableURLSpan[] lcus = ssb.getSpans(0, ssb.length(), LongClickableURLSpan.class); 75 | if (lcus != null) { 76 | for (LongClickableURLSpan span : lcus) { 77 | int start = ssb.getSpanStart(span); 78 | int end = ssb.getSpanEnd(span); 79 | int flags = ssb.getSpanFlags(span); 80 | LongClickableURLSpan copy = span.copy(); 81 | ssb.removeSpan(span); 82 | ssb.setSpan(copy, start, end, flags); 83 | } 84 | } 85 | 86 | return ssb; 87 | } 88 | 89 | void clear(Object tag) { 90 | HashSet> richTexts = instances.get(tag); 91 | if (richTexts != null) { 92 | for (WeakReference weakReference : richTexts) { 93 | RichText richText = weakReference.get(); 94 | if (richText != null) { 95 | richText.clear(); 96 | } 97 | } 98 | } 99 | instances.remove(tag); 100 | } 101 | 102 | void bind(Object tag, RichText richText) { 103 | HashSet> richTexts = instances.get(tag); 104 | if (richTexts == null) { 105 | richTexts = new HashSet<>(); 106 | instances.put(tag, richTexts); 107 | } 108 | richTexts.add(new WeakReference<>(richText)); 109 | } 110 | 111 | 112 | private static class RichTextPoolHolder { 113 | private static final RichTextPool RICH_TEXT_POOL = new RichTextPool(); 114 | } 115 | 116 | public static RichTextPool getPool() { 117 | return RichTextPoolHolder.RICH_TEXT_POOL; 118 | } 119 | 120 | public void recycle() { 121 | richCache.evictAll(); 122 | } 123 | 124 | } 125 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/RichType.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext; 2 | 3 | /** 4 | * Created by zhou on 16-7-27. 5 | * 富文本类型 6 | */ 7 | public enum RichType { 8 | html, markdown 9 | } 10 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/cache/BitmapPool.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.cache; 2 | 3 | import android.graphics.Bitmap; 4 | import android.util.LruCache; 5 | 6 | import com.jakewharton.disklrucache.DiskLruCache; 7 | import com.zzhoujay.richtext.drawable.DrawableSizeHolder; 8 | import com.zzhoujay.richtext.ext.Debug; 9 | 10 | import java.io.File; 11 | import java.io.IOException; 12 | import java.io.InputStream; 13 | 14 | /** 15 | * Created by zhou on 2017/3/25. 16 | * Bitmap cache pool 17 | */ 18 | public class BitmapPool { 19 | 20 | private static final String RICH_TEXT_DIR_NAME = "_rt"; 21 | private static final int MAX_SIZE_LOCAL_CACHE_SIZE = 1024 * 1024; 22 | private static final int MAX_TEMP_LOCAL_CACHE_SIZE = 1024 * 1024 * 500; 23 | 24 | 25 | private static final int bitmapCacheSize = (int) (Runtime.getRuntime().maxMemory() / 4); 26 | private static final int MAX_SIZE_CACHE_SIZE = 100; 27 | private static final String SIZE_DIR_NAME = "_s"; 28 | private static final String TEMP_DIR_NAME = "_t"; 29 | 30 | private final LruCache bitmapCache; 31 | private final LruCache sizeHolderCache; 32 | private static File cacheDir; 33 | private static final int version = 1; 34 | 35 | private static DiskLruCache sizeDiskLruCache; 36 | private static DiskLruCache tempDiskLruCache; 37 | 38 | private static File sizeDir; 39 | private static File tempDir; 40 | 41 | private BitmapPool() { 42 | bitmapCache = new LruCache(bitmapCacheSize) { 43 | @Override 44 | protected int sizeOf(String key, Bitmap bitmap) { 45 | return bitmap == null ? 0 : bitmap.getRowBytes() * bitmap.getHeight(); 46 | } 47 | }; 48 | sizeHolderCache = new LruCache<>(MAX_SIZE_CACHE_SIZE); 49 | } 50 | 51 | public void cacheBitmap(String key, Bitmap bitmap) { 52 | bitmapCache.put(key, bitmap); 53 | } 54 | 55 | public void cacheSize(String key, DrawableSizeHolder drawableSizeHolder) { 56 | sizeHolderCache.put(key, drawableSizeHolder); 57 | CacheIOHelper.SIZE_CACHE_IO_HELPER.writeToCache(key, drawableSizeHolder, getSizeDiskLruCache()); 58 | } 59 | 60 | public void cache(String key, Bitmap bitmap, DrawableSizeHolder drawableSizeHolder) { 61 | cacheBitmap(key, bitmap); 62 | cacheSize(key, drawableSizeHolder); 63 | } 64 | 65 | public Bitmap getBitmap(String key) { 66 | return bitmapCache.get(key); 67 | } 68 | 69 | public DrawableSizeHolder getSizeHolder(String key) { 70 | DrawableSizeHolder drawableSizeHolder = sizeHolderCache.get(key); 71 | if (drawableSizeHolder == null) { 72 | drawableSizeHolder = CacheIOHelper.SIZE_CACHE_IO_HELPER.readFromCache(key, getSizeDiskLruCache()); 73 | } 74 | return drawableSizeHolder; 75 | } 76 | 77 | public void writeBitmapToTemp(String key, InputStream inputStream) { 78 | CacheIOHelper.REMOTE_IMAGE_CACHE_IO_HELPER.writeToCache(key, inputStream, getTempDiskLruCache()); 79 | } 80 | 81 | public InputStream readBitmapFromTemp(String key) { 82 | return CacheIOHelper.REMOTE_IMAGE_CACHE_IO_HELPER.readFromCache(key, getTempDiskLruCache()); 83 | } 84 | 85 | public boolean hasBitmapLocalCache(String key) { 86 | return CacheIOHelper.REMOTE_IMAGE_CACHE_IO_HELPER.hasCache(key, getTempDiskLruCache()); 87 | } 88 | 89 | private static class BitmapPoolHolder { 90 | private static final BitmapPool BITMAP_POOL = new BitmapPool(); 91 | } 92 | 93 | public static BitmapPool getPool() { 94 | return BitmapPoolHolder.BITMAP_POOL; 95 | } 96 | 97 | public static void setCacheDir(File cacheDir) { 98 | if (BitmapPool.cacheDir == null && cacheDir != null) { 99 | BitmapPool.cacheDir = cacheDir; 100 | File richTextDir = new File(cacheDir, RICH_TEXT_DIR_NAME); 101 | if (!richTextDir.exists()) { 102 | //noinspection ResultOfMethodCallIgnored 103 | richTextDir.mkdir(); 104 | } 105 | sizeDir = new File(richTextDir, SIZE_DIR_NAME); 106 | if (!sizeDir.exists()) { 107 | //noinspection ResultOfMethodCallIgnored 108 | sizeDir.mkdir(); 109 | } 110 | tempDir = new File(richTextDir, TEMP_DIR_NAME); 111 | if (!tempDir.exists()) { 112 | //noinspection ResultOfMethodCallIgnored 113 | tempDir.mkdir(); 114 | } 115 | } 116 | } 117 | 118 | public static int getVersion() { 119 | return version; 120 | } 121 | 122 | public void clear() { 123 | bitmapCache.evictAll(); 124 | sizeHolderCache.evictAll(); 125 | } 126 | 127 | @SuppressWarnings("unused") 128 | public void clearLocalDiskCache() { 129 | try { 130 | DiskLruCache sizeDiskLruCache = getSizeDiskLruCache(); 131 | if (sizeDiskLruCache != null) { 132 | sizeDiskLruCache.delete(); 133 | } 134 | } catch (IOException e) { 135 | Debug.e(e); 136 | } 137 | } 138 | 139 | private static DiskLruCache getSizeDiskLruCache() { 140 | 141 | if (sizeDiskLruCache == null && cacheDir != null) { 142 | try { 143 | sizeDiskLruCache = DiskLruCache.open(sizeDir, version, 1, MAX_SIZE_LOCAL_CACHE_SIZE); 144 | } catch (IOException e) { 145 | Debug.e(e); 146 | } 147 | } 148 | 149 | return sizeDiskLruCache; 150 | } 151 | 152 | private static DiskLruCache getTempDiskLruCache() { 153 | if (tempDiskLruCache == null && cacheDir != null) { 154 | try { 155 | tempDiskLruCache = DiskLruCache.open(tempDir, version, 1, MAX_TEMP_LOCAL_CACHE_SIZE); 156 | } catch (IOException e) { 157 | Debug.e(e); 158 | } 159 | } 160 | return tempDiskLruCache; 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/cache/CacheIOHelper.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.cache; 2 | 3 | import com.jakewharton.disklrucache.DiskLruCache; 4 | import com.zzhoujay.richtext.callback.BitmapStream; 5 | import com.zzhoujay.richtext.drawable.DrawableSizeHolder; 6 | import com.zzhoujay.richtext.ext.Debug; 7 | 8 | import java.io.IOException; 9 | import java.io.InputStream; 10 | import java.io.OutputStream; 11 | 12 | /** 13 | * Created by zhou on 2017/10/21. 14 | * CacheIOHelper 15 | */ 16 | 17 | interface CacheIOHelper { 18 | 19 | int BUFFER_SIZE = 1024; 20 | 21 | CacheIOHelper SIZE_CACHE_IO_HELPER = new CacheIOHelper() { 22 | @Override 23 | public void writeToCache(String key, DrawableSizeHolder input, DiskLruCache cache) { 24 | if (cache != null) { 25 | 26 | try { 27 | DiskLruCache.Editor edit = cache.edit(key); 28 | 29 | if (edit == null) { 30 | return; 31 | } 32 | 33 | OutputStream outputStream = edit.newOutputStream(0); 34 | 35 | input.save(outputStream); 36 | 37 | outputStream.flush(); 38 | outputStream.close(); 39 | 40 | edit.commit(); 41 | } catch (IOException e) { 42 | Debug.e(e); 43 | } 44 | } 45 | } 46 | 47 | @Override 48 | public DrawableSizeHolder readFromCache(String key, DiskLruCache cache) { 49 | if (cache != null) { 50 | 51 | try { 52 | DiskLruCache.Snapshot snapshot = cache.get(key); 53 | 54 | if (snapshot == null) { 55 | return null; 56 | } 57 | 58 | InputStream inputStream = snapshot.getInputStream(0); 59 | 60 | DrawableSizeHolder drawableSizeHolder = DrawableSizeHolder.read(inputStream, key); 61 | 62 | inputStream.close(); 63 | 64 | return drawableSizeHolder; 65 | } catch (IOException e) { 66 | Debug.e(e); 67 | } 68 | } 69 | return null; 70 | } 71 | 72 | @Override 73 | public boolean hasCache(String key, DiskLruCache cache) { 74 | if (cache != null) { 75 | try { 76 | DiskLruCache.Snapshot snapshot = cache.get(key); 77 | return snapshot != null; 78 | } catch (IOException e) { 79 | Debug.e(e); 80 | } 81 | } 82 | return false; 83 | } 84 | }; 85 | 86 | CacheIOHelper REMOTE_IMAGE_CACHE_IO_HELPER = new CacheIOHelper() { 87 | @Override 88 | public void writeToCache(String key, InputStream input, DiskLruCache cache) { 89 | if (cache != null) { 90 | 91 | try { 92 | DiskLruCache.Editor edit = cache.edit(key); 93 | 94 | if (edit == null) { 95 | return; 96 | } 97 | 98 | OutputStream outputStream = edit.newOutputStream(0); 99 | 100 | byte[] buffer = new byte[BUFFER_SIZE]; 101 | 102 | int len; 103 | 104 | while ((len = input.read(buffer)) != -1) { 105 | outputStream.write(buffer, 0, len); 106 | } 107 | 108 | outputStream.flush(); 109 | outputStream.close(); 110 | 111 | input.close(); 112 | 113 | edit.commit(); 114 | } catch (IOException e) { 115 | Debug.e(e); 116 | } 117 | 118 | } 119 | } 120 | 121 | @Override 122 | public InputStream readFromCache(String key, DiskLruCache cache) { 123 | if (cache != null) { 124 | 125 | DiskLruCache.Snapshot snapshot = null; 126 | try { 127 | snapshot = cache.get(key); 128 | } catch (IOException e) { 129 | Debug.e(e); 130 | } 131 | return snapshot == null ? null : snapshot.getInputStream(0); 132 | } 133 | return null; 134 | } 135 | 136 | @Override 137 | public boolean hasCache(String key, DiskLruCache cache) { 138 | if (cache != null) { 139 | try { 140 | DiskLruCache.Snapshot snapshot = cache.get(key); 141 | return snapshot != null; 142 | } catch (IOException e) { 143 | Debug.e(e); 144 | } 145 | } 146 | return false; 147 | } 148 | }; 149 | 150 | 151 | void writeToCache(String key, INPUT input, DiskLruCache cache); 152 | 153 | OUTPUT readFromCache(String key, DiskLruCache cache); 154 | 155 | boolean hasCache(String key, DiskLruCache cache); 156 | 157 | 158 | } 159 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/callback/BitmapStream.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.callback; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | 6 | /** 7 | * Created by zhou on 2017/11/17. 8 | */ 9 | 10 | public interface BitmapStream extends Closeable { 11 | 12 | InputStream getInputStream() throws IOException; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/callback/Callback.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.callback; 2 | 3 | /** 4 | * Created by zhou on 2017/3/11. 5 | * 解析完成回调接口 6 | */ 7 | 8 | public interface Callback { 9 | 10 | /** 11 | * 解析完成回调 12 | * 13 | * @param imageLoadDone 图片全部加载成功 14 | */ 15 | void done(boolean imageLoadDone); 16 | 17 | } 18 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/callback/Closeable.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.callback; 2 | 3 | import java.io.IOException; 4 | 5 | /** 6 | * Created by zhou on 2017/11/17. 7 | */ 8 | 9 | public interface Closeable { 10 | 11 | void close() throws IOException; 12 | 13 | } 14 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/callback/DrawableGetter.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.callback; 2 | 3 | import android.graphics.drawable.Drawable; 4 | import android.widget.TextView; 5 | 6 | import com.zzhoujay.richtext.ImageHolder; 7 | import com.zzhoujay.richtext.RichTextConfig; 8 | 9 | /** 10 | * Created by zhou on 2017/11/6. 11 | * DrawableGetter 12 | */ 13 | 14 | public interface DrawableGetter { 15 | 16 | /** 17 | * 获取图片 18 | * 19 | * @param holder ImageHolder 20 | * @param config RichTextConfig 21 | * @param textView TextView 22 | * @return Drawable 23 | * @see ImageHolder 24 | * @see RichTextConfig 25 | */ 26 | Drawable getDrawable(ImageHolder holder, RichTextConfig config, TextView textView); 27 | 28 | 29 | } -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/callback/ImageFixCallback.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.callback; 2 | 3 | import com.zzhoujay.richtext.ImageHolder; 4 | 5 | /** 6 | * Created by zhou on 16-5-28. 7 | * ImageFixCallback 8 | */ 9 | public interface ImageFixCallback { 10 | 11 | /** 12 | * 加载开始前 13 | * 14 | * @param holder ImageHolder 15 | */ 16 | void onInit(ImageHolder holder); 17 | 18 | /** 19 | * 正在加载,此时设置holder的宽高将会运用到placeholder 20 | * 21 | * @param holder ImageHolder 22 | */ 23 | void onLoading(ImageHolder holder); 24 | 25 | /** 26 | * 图片下载完成(未加载到内存)并且尺寸已获取,此时给holder设置最大宽高为图片加载到内存后的最大宽高,用与压缩图片 27 | * 28 | * @param holder ImageHolder 29 | * @param imageWidth 图片原始宽度 30 | * @param imageHeight 图片原始高度 31 | * @param sizeHolder 修改sizeHolder来改变图片的大小 32 | */ 33 | void onSizeReady(ImageHolder holder, int imageWidth, int imageHeight, ImageHolder.SizeHolder sizeHolder); 34 | 35 | /** 36 | * 图片已加载到内存,此时给holder设置宽高将是最后图片显示的大小 37 | * 38 | * @param holder ImageHolder 39 | * @param width 图片加载到内存后的宽度 40 | * @param height 图片加载到内存后的高度 41 | */ 42 | void onImageReady(ImageHolder holder, int width, int height); 43 | 44 | /** 45 | * 图片加载失败,此时设置holder的宽高将会运用到errorImage 46 | * 47 | * @param holder ImageHolder 48 | * @param e Exception 49 | */ 50 | void onFailure(ImageHolder holder, Exception e); 51 | 52 | } 53 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/callback/ImageGetter.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.callback; 2 | 3 | /** 4 | * Created by zhou on 2016/12/3. 5 | * 图片加载器 6 | */ 7 | public interface ImageGetter extends DrawableGetter, Recyclable { 8 | 9 | // /** 10 | // * 获取图片 11 | // * 12 | // * @param holder ImageHolder 13 | // * @param config RichTextConfig 14 | // * @param textView TextView 15 | // * @return Drawable 16 | // * @see ImageHolder 17 | // * @see RichTextConfig 18 | // */ 19 | // Drawable getDrawable(ImageHolder holder, RichTextConfig config, TextView textView); 20 | 21 | void registerImageLoadNotify(ImageLoadNotify imageLoadNotify); 22 | } -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/callback/ImageLoadNotify.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.callback; 2 | 3 | /** 4 | * Created by zhou on 16-10-24. 5 | * Image Load Notify 6 | */ 7 | public interface ImageLoadNotify { 8 | /** 9 | * 图片加载完成 10 | * 11 | * @param from Object 12 | */ 13 | void done(Object from); 14 | } 15 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/callback/LinkFixCallback.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.callback; 2 | 3 | import com.zzhoujay.richtext.LinkHolder; 4 | 5 | /** 6 | * Created by zhou on 2016/11/17. 7 | * LinkFixCallback 8 | */ 9 | public interface LinkFixCallback { 10 | 11 | void fix(LinkHolder holder); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/callback/OnImageClickListener.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.callback; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * Created by zhou on 16-5-28. 7 | * OnImageClickListener 8 | */ 9 | public interface OnImageClickListener { 10 | /** 11 | * 图片被点击后的回调方法 12 | * 13 | * @param imageUrls 本篇富文本内容里的全部图片 14 | * @param position 点击处图片在imageUrls中的位置 15 | */ 16 | void imageClicked(List imageUrls, int position); 17 | } -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/callback/OnImageLongClickListener.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.callback; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * Created by zhou on 16-8-4. 7 | * OnImageLongClickListener 8 | */ 9 | public interface OnImageLongClickListener { 10 | /** 11 | * 图片长按回调 12 | * 13 | * @param imageUrls  全部图片链接 14 | * @param position  当前图片位置 15 | * @return true:已处理,false:未处理并交由imageClicked处理 16 | */ 17 | boolean imageLongClicked(List imageUrls, int position); 18 | } 19 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/callback/OnUrlClickListener.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.callback; 2 | 3 | /** 4 | * Created by zhou on 16-5-28. 5 | * OnUrlClickListener 6 | */ 7 | public interface OnUrlClickListener { 8 | 9 | /** 10 | * 超链接点击得回调方法 11 | * 12 | * @param url 点击得url 13 | * @return true:已处理,false:未处理(会进行默认处理) 14 | */ 15 | boolean urlClicked(String url); 16 | } 17 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/callback/OnUrlLongClickListener.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.callback; 2 | 3 | /** 4 | * Created by zhou on 16-8-4. 5 | * OnUrlLongClickListener 6 | */ 7 | public interface OnUrlLongClickListener { 8 | 9 | /** 10 | * 链接长按回调 11 | * 12 | * @param url  链接 13 | * @return true:已处理,false:未处理并交给urlClick处理 14 | */ 15 | boolean urlLongClick(String url); 16 | 17 | } 18 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/callback/Recyclable.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.callback; 2 | 3 | /** 4 | * Created by zhou on 2016/12/4. 5 | * 标记为可回收的 6 | */ 7 | public interface Recyclable { 8 | 9 | /** 10 | * 回收资源 11 | */ 12 | void recycle(); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/callback/SimpleImageFixCallback.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.callback; 2 | 3 | import com.zzhoujay.richtext.ImageHolder; 4 | 5 | /** 6 | * Created by zhou on 2017/2/21. 7 | * SimpleImageFixCallback 8 | */ 9 | 10 | public abstract class SimpleImageFixCallback implements ImageFixCallback { 11 | 12 | @Override 13 | public void onInit(ImageHolder holder) { 14 | 15 | } 16 | 17 | @Override 18 | public void onLoading(ImageHolder holder) { 19 | 20 | } 21 | 22 | @Override 23 | public void onSizeReady(ImageHolder holder, int imageWidth, int imageHeight, ImageHolder.SizeHolder sizeHolder) { 24 | 25 | } 26 | 27 | @Override 28 | public void onImageReady(ImageHolder holder, int width, int height) { 29 | 30 | } 31 | 32 | @Override 33 | public void onFailure(ImageHolder holder, Exception e) { 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/drawable/DrawableBorderHolder.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.drawable; 2 | 3 | import android.graphics.Color; 4 | import androidx.annotation.ColorInt; 5 | 6 | /** 7 | * Created by zhou on 2017/10/4. 8 | * Drawable border 9 | */ 10 | public class DrawableBorderHolder { 11 | 12 | 13 | private boolean showBorder; 14 | private float borderSize; 15 | @ColorInt 16 | private int borderColor; 17 | private float radius; 18 | 19 | DrawableBorderHolder(boolean showBorder, float borderSize, @ColorInt int borderColor, float radius) { 20 | this.showBorder = showBorder; 21 | this.borderSize = borderSize; 22 | this.borderColor = borderColor; 23 | this.radius = radius; 24 | } 25 | 26 | public DrawableBorderHolder() { 27 | this(false, 5, Color.BLACK, 0); 28 | } 29 | 30 | public DrawableBorderHolder(DrawableBorderHolder borderHolder) { 31 | this(borderHolder.showBorder, borderHolder.borderSize, borderHolder.borderColor, borderHolder.radius); 32 | } 33 | 34 | boolean isShowBorder() { 35 | return showBorder; 36 | } 37 | 38 | public void setShowBorder(boolean showBorder) { 39 | this.showBorder = showBorder; 40 | } 41 | 42 | float getBorderSize() { 43 | return borderSize; 44 | } 45 | 46 | public void setBorderSize(float borderSize) { 47 | this.borderSize = borderSize; 48 | } 49 | 50 | @ColorInt 51 | int getBorderColor() { 52 | return borderColor; 53 | } 54 | 55 | public void setBorderColor(@ColorInt int borderColor) { 56 | this.borderColor = borderColor; 57 | } 58 | 59 | float getRadius() { 60 | return radius; 61 | } 62 | 63 | public void setRadius(float radius) { 64 | this.radius = radius; 65 | } 66 | 67 | 68 | void set(DrawableBorderHolder borderHolder) { 69 | this.showBorder = borderHolder.showBorder; 70 | this.borderSize = borderHolder.borderSize; 71 | this.borderColor = borderHolder.borderColor; 72 | this.radius = borderHolder.radius; 73 | } 74 | 75 | @SuppressWarnings("RedundantIfStatement") 76 | @Override 77 | public boolean equals(Object o) { 78 | if (this == o) return true; 79 | if (!(o instanceof DrawableBorderHolder)) return false; 80 | 81 | DrawableBorderHolder that = (DrawableBorderHolder) o; 82 | 83 | if (showBorder != that.showBorder) return false; 84 | if (Float.compare(that.borderSize, borderSize) != 0) return false; 85 | if (borderColor != that.borderColor) return false; 86 | if (Float.compare(that.radius, radius) != 0) return false; 87 | 88 | return true; 89 | } 90 | 91 | @Override 92 | public int hashCode() { 93 | int result = (showBorder ? 1 : 0); 94 | result = 31 * result + (borderSize != +0.0f ? Float.floatToIntBits(borderSize) : 0); 95 | result = 31 * result + borderColor; 96 | result = 31 * result + (radius != +0.0f ? Float.floatToIntBits(radius) : 0); 97 | return result; 98 | } 99 | 100 | 101 | } 102 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/drawable/DrawableSizeHolder.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.drawable; 2 | 3 | import android.graphics.RectF; 4 | 5 | import com.zzhoujay.richtext.ImageHolder; 6 | import com.zzhoujay.richtext.ext.Debug; 7 | 8 | import java.io.IOException; 9 | import java.io.InputStream; 10 | import java.io.OutputStream; 11 | 12 | /** 13 | * Created by zhou on 2017/10/2. 14 | * DrawableSizeHolder 15 | */ 16 | @SuppressWarnings("unused") 17 | public class DrawableSizeHolder { 18 | 19 | RectF border; 20 | ImageHolder.ScaleType scaleType; 21 | private String name; 22 | DrawableBorderHolder borderHolder; 23 | 24 | private DrawableSizeHolder(String name, RectF border, ImageHolder.ScaleType scaleType, DrawableBorderHolder borderHolder) { 25 | this.border = border; 26 | this.scaleType = scaleType; 27 | this.name = name; 28 | this.borderHolder = borderHolder; 29 | } 30 | 31 | DrawableSizeHolder(ImageHolder holder) { 32 | this( 33 | holder.getKey(), 34 | new RectF(0, 0, holder.getWidth(), holder.getHeight()), 35 | holder.getScaleType(), 36 | new DrawableBorderHolder(holder.getBorderHolder()) 37 | ); 38 | } 39 | 40 | void set(DrawableSizeHolder sizeHolder) { 41 | this.borderHolder.set(sizeHolder.borderHolder); 42 | this.border.set(sizeHolder.border); 43 | this.scaleType = sizeHolder.scaleType; 44 | this.name = sizeHolder.name; 45 | } 46 | 47 | public void save(OutputStream fos) { 48 | try { 49 | writeFloat(fos, border.left); 50 | writeFloat(fos, border.top); 51 | writeFloat(fos, border.right); 52 | writeFloat(fos, border.bottom); 53 | writeInt(fos, scaleType.intValue()); 54 | writeBoolean(fos, borderHolder.isShowBorder()); 55 | writeInt(fos, borderHolder.getBorderColor()); 56 | writeFloat(fos, borderHolder.getBorderSize()); 57 | writeFloat(fos, borderHolder.getRadius()); 58 | fos.flush(); 59 | fos.close(); 60 | } catch (IOException e) { 61 | Debug.e(e); 62 | } 63 | } 64 | 65 | public static DrawableSizeHolder read(InputStream fis, String name) { 66 | try { 67 | float left = readFloat(fis); 68 | float top = readFloat(fis); 69 | float right = readFloat(fis); 70 | float bottom = readFloat(fis); 71 | int scaleType = readInt(fis); 72 | boolean showBorder = readBoolean(fis); 73 | int color = readInt(fis); 74 | float borderSize = readFloat(fis); 75 | float borderRadius = readFloat(fis); 76 | fis.close(); 77 | RectF border = new RectF(left, top, right, bottom); 78 | DrawableBorderHolder borderHolder = new DrawableBorderHolder(showBorder, borderSize, color, borderRadius); 79 | return new DrawableSizeHolder(name, border, ImageHolder.ScaleType.valueOf(scaleType), borderHolder); 80 | } catch (IOException e) { 81 | Debug.e(e); 82 | } 83 | return null; 84 | } 85 | 86 | 87 | private static void writeBoolean(OutputStream stream, boolean b) throws IOException { 88 | stream.write(b ? 1 : 0); 89 | } 90 | 91 | private static boolean readBoolean(InputStream stream) throws IOException { 92 | return stream.read() != 0; 93 | } 94 | 95 | private static int readInt(InputStream stream) throws IOException { 96 | byte[] bs = new byte[4]; 97 | //noinspection ResultOfMethodCallIgnored 98 | stream.read(bs); 99 | return byte2int(bs); 100 | } 101 | 102 | private static void writeInt(OutputStream stream, int i) throws IOException { 103 | stream.write(int2byte(i)); 104 | } 105 | 106 | private static void writeFloat(OutputStream stream, float f) throws IOException { 107 | stream.write(int2byte(Float.floatToIntBits(f))); 108 | } 109 | 110 | private static float readFloat(InputStream stream) throws IOException { 111 | return Float.intBitsToFloat(readInt(stream)); 112 | } 113 | 114 | 115 | private static byte[] int2byte(int res) { 116 | byte[] targets = new byte[4]; 117 | 118 | targets[0] = (byte) (res & 0xff);// 最低位 119 | targets[1] = (byte) ((res >> 8) & 0xff);// 次低位 120 | targets[2] = (byte) ((res >> 16) & 0xff);// 次高位 121 | targets[3] = (byte) (res >>> 24);// 最高位,无符号右移。 122 | return targets; 123 | } 124 | 125 | private static int byte2int(byte[] res) { 126 | return (res[0] & 0xff) | ((res[1] << 8) & 0xff00) // | 表示安位或 127 | | ((res[2] << 24) >>> 8) | (res[3] << 24); 128 | } 129 | 130 | public RectF getBorder() { 131 | return border; 132 | } 133 | 134 | public ImageHolder.ScaleType getScaleType() { 135 | return scaleType; 136 | } 137 | 138 | public String getName() { 139 | return name; 140 | } 141 | 142 | public DrawableBorderHolder getBorderHolder() { 143 | return borderHolder; 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/drawable/GifDrawable.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.drawable; 2 | 3 | import android.graphics.Canvas; 4 | import android.graphics.ColorFilter; 5 | import android.graphics.Movie; 6 | import android.graphics.Paint; 7 | import android.graphics.PixelFormat; 8 | import android.graphics.Rect; 9 | import android.graphics.drawable.Drawable; 10 | import android.os.Handler; 11 | import android.os.Looper; 12 | import android.os.Message; 13 | import androidx.annotation.NonNull; 14 | import android.widget.TextView; 15 | 16 | /** 17 | * Created by zhou on 2017/2/21. 18 | * Support for custom Drawable playing Gif images 19 | */ 20 | 21 | public class GifDrawable extends Drawable { 22 | 23 | private static final int what = 0x357; 24 | 25 | private Movie movie; 26 | private long start; 27 | private int height; 28 | private int width; 29 | private boolean running; 30 | private TextView textView; 31 | private float scaleX; 32 | private float scaleY; 33 | private Paint paint; 34 | 35 | private Handler handler; 36 | 37 | public GifDrawable(Movie movie, int height, int width) { 38 | this.movie = movie; 39 | this.height = height; 40 | this.width = width; 41 | setBounds(0, 0, width, height); 42 | scaleX = scaleY = 1.0f; 43 | paint = new Paint(); 44 | handler = new Handler(Looper.getMainLooper()) { 45 | @Override 46 | public void handleMessage(Message msg) { 47 | if (msg.what == what && running && textView != null) { 48 | textView.invalidate(); 49 | sendEmptyMessageDelayed(what, 33); 50 | } 51 | } 52 | }; 53 | } 54 | 55 | @Override 56 | public void draw(@NonNull Canvas canvas) { 57 | long now = android.os.SystemClock.uptimeMillis(); 58 | if (start == 0) { // first time 59 | start = now; 60 | } 61 | if (movie != null) { 62 | int dur = movie.duration(); 63 | if (dur == 0) { 64 | dur = 1000; 65 | } 66 | int relTime = (int) ((now - start) % dur); 67 | movie.setTime(relTime); 68 | Rect bounds = getBounds(); 69 | canvas.scale(scaleX, scaleY); 70 | movie.draw(canvas, bounds.left, bounds.top); 71 | } 72 | } 73 | 74 | @Override 75 | public void setBounds(@NonNull Rect bounds) { 76 | super.setBounds(bounds); 77 | calculateScale(); 78 | } 79 | 80 | @Override 81 | public void setBounds(int left, int top, int right, int bottom) { 82 | super.setBounds(left, top, right, bottom); 83 | calculateScale(); 84 | } 85 | 86 | private void calculateScale() { 87 | scaleX = (float) getBounds().width() / width; 88 | scaleY = (float) getBounds().height() / height; 89 | } 90 | 91 | public void start(TextView textView) { 92 | running = true; 93 | this.textView = textView; 94 | handler.sendEmptyMessage(what); 95 | } 96 | 97 | public void stop() { 98 | running = false; 99 | this.textView = null; 100 | this.movie = null; 101 | } 102 | 103 | @Override 104 | public void setAlpha(int alpha) { 105 | paint.setAlpha(alpha); 106 | } 107 | 108 | @Override 109 | public void setColorFilter(ColorFilter colorFilter) { 110 | paint.setColorFilter(colorFilter); 111 | } 112 | 113 | @Override 114 | public int getIntrinsicHeight() { 115 | return height; 116 | } 117 | 118 | @Override 119 | public int getIntrinsicWidth() { 120 | return width; 121 | } 122 | 123 | @Override 124 | public int getOpacity() { 125 | return PixelFormat.TRANSLUCENT; 126 | } 127 | 128 | public int getHeight() { 129 | return height; 130 | } 131 | 132 | public int getWidth() { 133 | return width; 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/exceptions/BitmapCacheException.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.exceptions; 2 | 3 | /** 4 | * Created by zhou on 2017/10/7. 5 | * BitmapCacheException 6 | */ 7 | 8 | @SuppressWarnings("unused") 9 | public class BitmapCacheException extends RuntimeException { 10 | 11 | private static final String MESSAGE = "Bitmap缓存过程异常"; 12 | 13 | public BitmapCacheException() { 14 | super(MESSAGE); 15 | } 16 | 17 | public BitmapCacheException(Throwable cause) { 18 | super(MESSAGE, cause); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/exceptions/BitmapCacheLoadFailureException.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.exceptions; 2 | 3 | import android.annotation.TargetApi; 4 | import android.os.Build; 5 | 6 | /** 7 | * Created by zhou on 2017/4/4. 8 | * BitmapCacheLoadFailureException 9 | */ 10 | 11 | @SuppressWarnings("unused") 12 | public class BitmapCacheLoadFailureException extends Exception { 13 | 14 | private static final String MESSAGE = "Bitmap 缓存加载失败"; 15 | 16 | public BitmapCacheLoadFailureException() { 17 | super(MESSAGE); 18 | } 19 | 20 | public BitmapCacheLoadFailureException(Throwable cause) { 21 | super(MESSAGE, cause); 22 | } 23 | 24 | @TargetApi(Build.VERSION_CODES.N) 25 | public BitmapCacheLoadFailureException(Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 26 | super(MESSAGE, cause, enableSuppression, writableStackTrace); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/exceptions/BitmapCacheNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.exceptions; 2 | 3 | import android.annotation.TargetApi; 4 | import android.os.Build; 5 | 6 | /** 7 | * Created by zhou on 2017/4/4. 8 | * BitmapCacheNotFoundException 9 | */ 10 | 11 | @SuppressWarnings("unused") 12 | public class BitmapCacheNotFoundException extends Exception { 13 | 14 | private static final String MESSAGE = "Bitmap 缓存不存在"; 15 | 16 | public BitmapCacheNotFoundException() { 17 | super(MESSAGE); 18 | } 19 | 20 | public BitmapCacheNotFoundException(Throwable cause) { 21 | super(MESSAGE, cause); 22 | } 23 | 24 | @TargetApi(Build.VERSION_CODES.N) 25 | public BitmapCacheNotFoundException(Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 26 | super(MESSAGE, cause, enableSuppression, writableStackTrace); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/exceptions/BitmapInputStreamNullPointException.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.exceptions; 2 | 3 | /** 4 | * Created by zhou on 2017/10/2. 5 | * BitmapInputStreamNullPointException 6 | */ 7 | 8 | public class BitmapInputStreamNullPointException extends RuntimeException { 9 | 10 | 11 | private static final String MESSAGE = "Bitmap InputStream cannot be null"; 12 | 13 | public BitmapInputStreamNullPointException() { 14 | super(MESSAGE); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/exceptions/HttpResponseCodeException.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.exceptions; 2 | 3 | /** 4 | * Created by zhou on 2017/11/5. 5 | * HttpResponseCodeException 6 | */ 7 | 8 | public class HttpResponseCodeException extends RuntimeException { 9 | 10 | public HttpResponseCodeException(int code) { 11 | super("Http Response Code is :" + code); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/exceptions/ImageDecodeException.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.exceptions; 2 | 3 | import android.annotation.TargetApi; 4 | import android.os.Build; 5 | 6 | import java.io.PrintStream; 7 | import java.io.PrintWriter; 8 | 9 | /** 10 | * Created by zhou on 2017/4/4. 11 | * ImageDecodeException 12 | */ 13 | 14 | public class ImageDecodeException extends Exception { 15 | 16 | private static final String IMAGE_DECODE_FAILURE = "Image Decode Failure"; 17 | 18 | private OutOfMemoryError error; 19 | 20 | public ImageDecodeException() { 21 | super(IMAGE_DECODE_FAILURE); 22 | } 23 | 24 | public ImageDecodeException(Throwable cause) { 25 | super(IMAGE_DECODE_FAILURE, cause); 26 | if (cause instanceof OutOfMemoryError) { 27 | error = (OutOfMemoryError) cause; 28 | } 29 | } 30 | 31 | @SuppressWarnings("unused") 32 | @TargetApi(Build.VERSION_CODES.N) 33 | public ImageDecodeException(Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 34 | super(IMAGE_DECODE_FAILURE, cause, enableSuppression, writableStackTrace); 35 | if (cause instanceof OutOfMemoryError) { 36 | error = (OutOfMemoryError) cause; 37 | } 38 | } 39 | 40 | @Override 41 | public void printStackTrace() { 42 | if (error != null) { 43 | error.printStackTrace(); 44 | } else { 45 | super.printStackTrace(); 46 | } 47 | } 48 | 49 | @Override 50 | public void printStackTrace(PrintStream s) { 51 | if (error != null) { 52 | error.printStackTrace(s); 53 | } else { 54 | super.printStackTrace(s); 55 | } 56 | } 57 | 58 | @Override 59 | public void printStackTrace(PrintWriter s) { 60 | if (error != null) { 61 | error.printStackTrace(s); 62 | } else { 63 | super.printStackTrace(s); 64 | } 65 | } 66 | 67 | 68 | } 69 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/exceptions/ImageDownloadTaskAddFailureException.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.exceptions; 2 | 3 | /** 4 | * Created by zhou on 2017/11/5. 5 | * ImageDownloadTaskAddFailureException 6 | */ 7 | 8 | public class ImageDownloadTaskAddFailureException extends RuntimeException { 9 | 10 | public ImageDownloadTaskAddFailureException() { 11 | super("Image download task add failure"); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/exceptions/ImageDownloaderNonExistenceException.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.exceptions; 2 | 3 | /** 4 | * Created by zhou on 2017/9/11. 5 | * 图片加载器不存在,异常 6 | */ 7 | 8 | public class ImageDownloaderNonExistenceException extends RuntimeException { 9 | 10 | public ImageDownloaderNonExistenceException() { 11 | super("ImageDownloader 为空或未设置"); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/exceptions/ImageLoadCancelledException.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.exceptions; 2 | 3 | /** 4 | * Created by zhou on 2017/11/5. 5 | * ImageLoadCancelledException 6 | */ 7 | 8 | public class ImageLoadCancelledException extends Exception { 9 | 10 | public ImageLoadCancelledException() { 11 | super("Image load has been cancelled"); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/exceptions/ImageWrapperMultiSourceException.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.exceptions; 2 | 3 | /** 4 | * Created by zhou on 2017/4/4. 5 | * ImageWrapperMultiSourceException 6 | */ 7 | 8 | public class ImageWrapperMultiSourceException extends IllegalArgumentException { 9 | 10 | private static final String MESSAGE = "GifDrawable和Bitmap有且只有一个为null"; 11 | 12 | public ImageWrapperMultiSourceException() { 13 | super(MESSAGE); 14 | } 15 | 16 | @SuppressWarnings("unused") 17 | public ImageWrapperMultiSourceException(Throwable cause) { 18 | super(MESSAGE, cause); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/exceptions/ResetImageSourceException.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.exceptions; 2 | 3 | import android.annotation.TargetApi; 4 | import android.os.Build; 5 | 6 | /** 7 | * Created by zhou on 2017/4/4. 8 | */ 9 | 10 | public class ResetImageSourceException extends RuntimeException { 11 | 12 | private static final String MESSAGE = "ImageHolder的source只能在INIT阶段修改"; 13 | 14 | public ResetImageSourceException() { 15 | super(MESSAGE); 16 | } 17 | 18 | public ResetImageSourceException(Throwable cause) { 19 | super(MESSAGE, cause); 20 | } 21 | 22 | @TargetApi(Build.VERSION_CODES.N) 23 | public ResetImageSourceException(Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 24 | super(MESSAGE, cause, enableSuppression, writableStackTrace); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ext/ContextKit.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ext; 2 | 3 | import android.app.Activity; 4 | import android.content.Context; 5 | import android.content.ContextWrapper; 6 | import android.os.Build; 7 | 8 | /** 9 | * Created by zhou on 2017/11/15. 10 | * ContextKit 11 | */ 12 | public class ContextKit { 13 | 14 | @SuppressWarnings("WeakerAccess") 15 | public static Activity getActivity(Context context) { 16 | if (context == null) { 17 | return null; 18 | } 19 | while (!(context instanceof Activity) && (context instanceof ContextWrapper)) { 20 | context = ((ContextWrapper) context).getBaseContext(); 21 | } 22 | if (context instanceof Activity) { 23 | return ((Activity) context); 24 | } else { 25 | return null; 26 | } 27 | } 28 | 29 | /** 30 | * 判断Activity是否已经结束 31 | * 32 | * @param context context 33 | * @return true:已结束 34 | */ 35 | public static boolean activityIsAlive(Context context) { 36 | Activity activity = getActivity(context); 37 | if (activity == null) { 38 | return false; 39 | } 40 | if (activity.isFinishing()) { 41 | return false; 42 | } else { 43 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed()) { 44 | return false; 45 | } 46 | } 47 | return true; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ext/Debug.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ext; 2 | 3 | import android.util.Log; 4 | 5 | import com.zzhoujay.richtext.RichText; 6 | 7 | /** 8 | * Created by zhou on 2017/4/4. 9 | * Debug Utils 10 | */ 11 | 12 | public class Debug { 13 | 14 | public static final String PREF = " --> "; 15 | private static final String TAG = "RichText"; 16 | 17 | public static void e(Throwable e) { 18 | if (RichText.debugMode) { 19 | e.printStackTrace(); 20 | } 21 | } 22 | 23 | public static void log(String tag, String message) { 24 | if (RichText.debugMode) { 25 | Log.i(TAG, tag + PREF + message); 26 | } 27 | } 28 | 29 | public static void log(String tag, String message, Throwable e) { 30 | if (RichText.debugMode) { 31 | Log.i(TAG, tag + PREF + message, e); 32 | } 33 | } 34 | 35 | public static void loge(String tag, String message, Throwable e) { 36 | Log.e(TAG, tag + PREF + message, e); 37 | } 38 | 39 | public static void loge(String tag, String message) { 40 | Log.e(TAG, tag + PREF + message); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ext/HtmlTagHandler.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ext; 2 | 3 | import android.graphics.Color; 4 | import android.text.Editable; 5 | import android.text.Html; 6 | import android.text.Spanned; 7 | import android.widget.TextView; 8 | 9 | import com.zzhoujay.markdown.style.CodeSpan; 10 | import com.zzhoujay.markdown.style.MarkDownBulletSpan; 11 | 12 | import org.xml.sax.XMLReader; 13 | 14 | import java.lang.ref.SoftReference; 15 | import java.util.Stack; 16 | 17 | /** 18 | * Created by zhou on 16-10-20. 19 | * 自定义标签的处理 20 | */ 21 | public class HtmlTagHandler implements Html.TagHandler { 22 | 23 | private static final int code_color = Color.parseColor("#F0F0F0"); 24 | private static final int h1_color = Color.parseColor("#333333"); 25 | 26 | 27 | private Stack stack; 28 | private Stack list; 29 | private int index = 0; 30 | private SoftReference textViewSoftReference; 31 | 32 | public HtmlTagHandler(TextView textView) { 33 | stack = new Stack<>(); 34 | list = new Stack<>(); 35 | this.textViewSoftReference = new SoftReference<>(textView); 36 | } 37 | 38 | @Override 39 | public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) { 40 | if (opening) { 41 | startTag(tag, output, xmlReader); 42 | stack.push(output.length()); 43 | } else { 44 | int len; 45 | if (stack.isEmpty()) { 46 | len = 0; 47 | } else { 48 | len = stack.pop(); 49 | } 50 | reallyHandler(len, output.length(), tag.toLowerCase(), output, xmlReader); 51 | } 52 | } 53 | 54 | @SuppressWarnings("unused") 55 | private void startTag(String tag, Editable out, XMLReader reader) { 56 | switch (tag.toLowerCase()) { 57 | case "ul": 58 | list.push(true); 59 | out.append('\n'); 60 | break; 61 | case "ol": 62 | list.push(false); 63 | out.append('\n'); 64 | break; 65 | case "pre": 66 | break; 67 | } 68 | } 69 | 70 | @SuppressWarnings("unused") 71 | private void reallyHandler(int start, int end, String tag, Editable out, XMLReader reader) { 72 | switch (tag.toLowerCase()) { 73 | case "code": 74 | CodeSpan cs = new CodeSpan(code_color); 75 | out.setSpan(cs, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 76 | break; 77 | case "ol": 78 | case "ul": 79 | out.append('\n'); 80 | if (!list.isEmpty()) 81 | list.pop(); 82 | break; 83 | case "li": 84 | boolean isUl = list.peek(); 85 | int i; 86 | if (isUl) { 87 | index = 0; 88 | i = -1; 89 | } else { 90 | i = ++index; 91 | } 92 | out.append('\n'); 93 | TextView textView = textViewSoftReference.get(); 94 | if (textView == null) { 95 | return; 96 | } 97 | MarkDownBulletSpan bulletSpan = new MarkDownBulletSpan(list.size() - 1, h1_color, i, textView); 98 | out.setSpan(bulletSpan, start, out.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 99 | break; 100 | } 101 | } 102 | 103 | } 104 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ext/ImageKit.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ext; 2 | 3 | import java.io.BufferedInputStream; 4 | import java.io.FileInputStream; 5 | import java.io.FileNotFoundException; 6 | import java.io.IOException; 7 | import java.io.InputStream; 8 | 9 | /** 10 | * Created by zhou on 2017/3/25. 11 | * ImageKit 12 | */ 13 | 14 | public class ImageKit { 15 | 16 | private static final String GIF_FILE_HEAD = "47494638"; 17 | 18 | public static boolean isGif(InputStream inputStream) { 19 | if (inputStream.markSupported()) { 20 | inputStream.mark(10); 21 | byte[] bs = new byte[4]; 22 | try { 23 | //noinspection ResultOfMethodCallIgnored 24 | inputStream.read(bs, 0, bs.length); 25 | inputStream.reset(); 26 | return GIF_FILE_HEAD.equals(bytesToHexString(bs)); 27 | } catch (IOException e) { 28 | e.printStackTrace(); 29 | } 30 | } 31 | return false; 32 | } 33 | 34 | public static boolean isGif(byte[] bytes) { 35 | byte[] bs = new byte[4]; 36 | System.arraycopy(bytes, 0, bs, 0, 4); 37 | return GIF_FILE_HEAD.equals(bytesToHexString(bs)); 38 | } 39 | 40 | public static boolean isGif(String path) { 41 | FileInputStream fileInputStream = null; 42 | BufferedInputStream bufferedInputStream = null; 43 | try { 44 | fileInputStream = new FileInputStream(path); 45 | bufferedInputStream = new BufferedInputStream(fileInputStream); 46 | return isGif(bufferedInputStream); 47 | } catch (FileNotFoundException e) { 48 | e.printStackTrace(); 49 | } finally { 50 | try { 51 | if (bufferedInputStream != null) { 52 | bufferedInputStream.close(); 53 | } 54 | if (fileInputStream != null) { 55 | fileInputStream.close(); 56 | } 57 | } catch (IOException e) { 58 | e.printStackTrace(); 59 | } 60 | } 61 | return false; 62 | } 63 | 64 | private static String bytesToHexString(byte[] src) { 65 | StringBuilder stringBuilder = new StringBuilder(); 66 | if (src == null || src.length <= 0) { 67 | return null; 68 | } 69 | for (byte aSrc : src) { 70 | int v = aSrc & 0xFF; 71 | String hv = Integer.toHexString(v); 72 | if (hv.length() < 2) { 73 | stringBuilder.append(0); 74 | } 75 | stringBuilder.append(hv); 76 | } 77 | return stringBuilder.toString(); 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ext/LongClickableLinkMovementMethod.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ext; 2 | 3 | import android.text.Layout; 4 | import android.text.Selection; 5 | import android.text.Spannable; 6 | import android.text.method.LinkMovementMethod; 7 | import android.view.MotionEvent; 8 | import android.widget.TextView; 9 | 10 | import com.zzhoujay.richtext.spans.ClickableImageSpan; 11 | import com.zzhoujay.richtext.spans.LongClickableSpan; 12 | 13 | /** 14 | * Created by zhou on 16-8-4. 15 | * 支持长按的MovementMethod 16 | */ 17 | public class LongClickableLinkMovementMethod extends LinkMovementMethod { 18 | 19 | private static final int MIN_INTERVAL = 500; 20 | 21 | private long lastTime; 22 | 23 | @Override 24 | public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { 25 | int action = event.getAction(); 26 | 27 | if (action == MotionEvent.ACTION_UP || 28 | action == MotionEvent.ACTION_DOWN) { 29 | int x = (int) event.getX(); 30 | int y = (int) event.getY(); 31 | 32 | x -= widget.getTotalPaddingLeft(); 33 | y -= widget.getTotalPaddingTop(); 34 | 35 | x += widget.getScrollX(); 36 | y += widget.getScrollY(); 37 | 38 | Layout layout = widget.getLayout(); 39 | int line = layout.getLineForVertical(y); 40 | int off = layout.getOffsetForHorizontal(line, x); 41 | 42 | LongClickableSpan[] link = buffer.getSpans(off, off, LongClickableSpan.class); 43 | 44 | if (link.length != 0) { 45 | long currTime = System.currentTimeMillis(); 46 | LongClickableSpan l = link[0]; 47 | int ls = buffer.getSpanStart(l); 48 | int le = buffer.getSpanEnd(l); 49 | // 判断点击的点是否在Image范围内 50 | ClickableImageSpan[] is = buffer.getSpans(ls, le, ClickableImageSpan.class); 51 | if (is.length > 0) { 52 | if (!is[0].clicked(x)) { 53 | Selection.removeSelection(buffer); 54 | return false; 55 | } 56 | } else if (off < layout.getOffsetToLeftOf(ls) || off > layout.getOffsetToLeftOf(le + 1)) { 57 | // 判断点击位置是否在链接范围内 58 | Selection.removeSelection(buffer); 59 | return false; 60 | } 61 | 62 | if (action == MotionEvent.ACTION_UP) { 63 | // 如果按下时间超过500毫秒,触发长按事件 64 | if (currTime - lastTime > MIN_INTERVAL) { 65 | if (!l.onLongClick(widget)) { 66 | // onLongClick返回false代表事件未处理,交由onClick处理 67 | l.onClick(widget); 68 | } 69 | } else { 70 | l.onClick(widget); 71 | } 72 | } else { 73 | Selection.setSelection(buffer, 74 | ls, le); 75 | } 76 | lastTime = currTime; 77 | return true; 78 | } else { 79 | Selection.removeSelection(buffer); 80 | return false; 81 | } 82 | } 83 | 84 | return super.onTouchEvent(widget, buffer, event); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ext/MD5.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ext; 2 | 3 | import java.math.BigInteger; 4 | import java.security.MessageDigest; 5 | import java.security.NoSuchAlgorithmException; 6 | 7 | /** 8 | * Created by zhou on 2016/12/5. 9 | * MD5 Utils 10 | */ 11 | 12 | public class MD5 { 13 | 14 | public static String generate(String source) { 15 | try { 16 | MessageDigest messageDigest = MessageDigest.getInstance("MD5"); 17 | messageDigest.update(source.getBytes()); 18 | return new BigInteger(1, messageDigest.digest()).toString(16); 19 | } catch (NoSuchAlgorithmException e) { 20 | e.printStackTrace(); 21 | } 22 | return source; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ext/TextKit.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ext; 2 | 3 | import android.text.TextUtils; 4 | 5 | /** 6 | * Created by zhou on 2017/2/21. 7 | * TextKit 8 | */ 9 | 10 | public class TextKit { 11 | 12 | private static final String ASSETS_PREFIX = "file:///android_asset/"; 13 | private static final String LOCAL_FILE_PREFIX = "/"; 14 | 15 | public static boolean isLocalPath(String path) { 16 | return !TextUtils.isEmpty(path) && path.startsWith(LOCAL_FILE_PREFIX); 17 | } 18 | 19 | public static boolean isAssetPath(String path) { 20 | return !TextUtils.isEmpty(path) && path.startsWith(ASSETS_PREFIX); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ig/AssetsImageLoader.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ig; 2 | 3 | import android.widget.TextView; 4 | 5 | import com.zzhoujay.richtext.ImageHolder; 6 | import com.zzhoujay.richtext.RichTextConfig; 7 | import com.zzhoujay.richtext.callback.ImageLoadNotify; 8 | import com.zzhoujay.richtext.drawable.DrawableWrapper; 9 | import com.zzhoujay.richtext.ext.Debug; 10 | 11 | import java.io.IOException; 12 | import java.io.InputStream; 13 | 14 | /** 15 | * Created by zhou on 2017/7/23. 16 | * Assets目录图片的加载器 17 | */ 18 | 19 | class AssetsImageLoader extends InputStreamImageLoader implements Runnable { 20 | 21 | private static final String ASSETS_PREFIX = "file:///android_asset/"; 22 | 23 | 24 | AssetsImageLoader(ImageHolder holder, RichTextConfig config, TextView textView, DrawableWrapper drawableWrapper, ImageLoadNotify iln) { 25 | super(holder, config, textView, drawableWrapper, iln, openAssetInputStream(holder, textView)); 26 | } 27 | 28 | private static InputStream openAssetInputStream(ImageHolder holder, TextView textView) { 29 | try { 30 | String fileName = getAssetFileName(holder.getSource()); 31 | InputStream inputStream; 32 | inputStream = textView.getContext().getAssets().open(fileName); 33 | return inputStream; 34 | } catch (IOException e) { 35 | Debug.e(e); 36 | } 37 | return null; 38 | } 39 | 40 | private static String getAssetFileName(String path) { 41 | if (path != null && path.startsWith(ASSETS_PREFIX)) { 42 | return path.replace(ASSETS_PREFIX, ""); 43 | } 44 | return null; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ig/Base64ImageLoader.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ig; 2 | 3 | import android.widget.TextView; 4 | 5 | import com.zzhoujay.richtext.ImageHolder; 6 | import com.zzhoujay.richtext.RichTextConfig; 7 | import com.zzhoujay.richtext.callback.ImageLoadNotify; 8 | import com.zzhoujay.richtext.drawable.DrawableWrapper; 9 | import com.zzhoujay.richtext.exceptions.ImageDecodeException; 10 | import com.zzhoujay.richtext.ext.Base64; 11 | 12 | /** 13 | * Created by zhou on 2016/12/9. 14 | * Base64格式图片解析器 15 | */ 16 | class Base64ImageLoader extends AbstractImageLoader implements Runnable { 17 | 18 | Base64ImageLoader(ImageHolder holder, RichTextConfig config, TextView textView, DrawableWrapper drawableWrapper, ImageLoadNotify iln) { 19 | super(holder, config, textView, drawableWrapper, iln, SourceDecode.BASE64_SOURCE_DECODE); 20 | } 21 | 22 | @Override 23 | public void run() { 24 | try { 25 | byte[] src = Base64.decode(holder.getSource()); 26 | doLoadImage(src); 27 | } catch (Exception e) { 28 | onFailure(new ImageDecodeException(e)); 29 | } catch (OutOfMemoryError error) { 30 | onFailure(new ImageDecodeException(error)); 31 | } 32 | } 33 | 34 | } -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ig/CallbackImageLoader.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ig; 2 | 3 | import android.widget.TextView; 4 | 5 | import com.zzhoujay.richtext.ImageHolder; 6 | import com.zzhoujay.richtext.RichTextConfig; 7 | import com.zzhoujay.richtext.cache.BitmapPool; 8 | import com.zzhoujay.richtext.callback.ImageLoadNotify; 9 | import com.zzhoujay.richtext.drawable.DrawableWrapper; 10 | import com.zzhoujay.richtext.exceptions.ImageDecodeException; 11 | 12 | import java.io.BufferedInputStream; 13 | import java.io.IOException; 14 | import java.io.InputStream; 15 | 16 | /** 17 | * Created by zhou on 2016/12/8. 18 | * 网络图片下载完成后被回调 19 | */ 20 | class CallbackImageLoader extends AbstractImageLoader { 21 | 22 | CallbackImageLoader(ImageHolder holder, RichTextConfig config, TextView textView, DrawableWrapper drawableWrapper, ImageLoadNotify iln) { 23 | super(holder, config, textView, drawableWrapper, iln, SourceDecode.INPUT_STREAM_DECODE); 24 | } 25 | 26 | void onImageDownloadFinish(String key, Exception exception) { 27 | if (exception != null) { 28 | onFailure(exception); 29 | return; 30 | } 31 | try { 32 | InputStream inputStream = BitmapPool.getPool().readBitmapFromTemp(key); 33 | BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); 34 | 35 | doLoadImage(bufferedInputStream); 36 | 37 | bufferedInputStream.close(); 38 | inputStream.close(); 39 | } catch (IOException e) { 40 | onFailure(e); 41 | } catch (OutOfMemoryError error) { 42 | onFailure(new ImageDecodeException(error)); 43 | } 44 | } 45 | 46 | } 47 | 48 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ig/Cancelable.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ig; 2 | 3 | /** 4 | * Created by zhou on 2016/12/11. 5 | * 可取消的任务(标记) 6 | */ 7 | public interface Cancelable { 8 | 9 | /** 10 | * 尝试取消(不一定能成功取消) 11 | */ 12 | void cancel(); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ig/DefaultImageDownloader.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ig; 2 | 3 | import android.annotation.SuppressLint; 4 | 5 | import com.zzhoujay.richtext.callback.BitmapStream; 6 | import com.zzhoujay.richtext.exceptions.HttpResponseCodeException; 7 | 8 | import java.io.IOException; 9 | import java.io.InputStream; 10 | import java.net.HttpURLConnection; 11 | import java.net.URL; 12 | import java.security.KeyManagementException; 13 | import java.security.NoSuchAlgorithmException; 14 | import java.security.SecureRandom; 15 | import java.security.cert.X509Certificate; 16 | 17 | import javax.net.ssl.HostnameVerifier; 18 | import javax.net.ssl.HttpsURLConnection; 19 | import javax.net.ssl.SSLContext; 20 | import javax.net.ssl.SSLSession; 21 | import javax.net.ssl.TrustManager; 22 | import javax.net.ssl.X509TrustManager; 23 | 24 | /** 25 | * Created by zhou on 2017/11/5. 26 | * 默认的图片下载器,使用HttpUrlConnect发起连接 27 | */ 28 | 29 | public class DefaultImageDownloader implements ImageDownloader { 30 | 31 | public static final String GLOBAL_ID = DefaultImageDownloader.class.getName(); 32 | 33 | @Override 34 | public BitmapStream download(String source) throws IOException { 35 | return new BitmapStreamImpl(source); 36 | } 37 | 38 | private static class BitmapStreamImpl implements BitmapStream { 39 | 40 | private final String url; 41 | private HttpURLConnection connection; 42 | private InputStream inputStream; 43 | 44 | private BitmapStreamImpl(String url) { 45 | this.url = url; 46 | } 47 | 48 | @Override 49 | public void close() throws IOException { 50 | if (inputStream != null) { 51 | inputStream.close(); 52 | } 53 | if (connection != null) { 54 | connection.disconnect(); 55 | } 56 | } 57 | 58 | @Override 59 | public InputStream getInputStream() throws IOException { 60 | URL url = new URL(this.url); 61 | connection = (HttpURLConnection) url.openConnection(); 62 | connection.setConnectTimeout(10000); 63 | connection.setDoInput(true); 64 | connection.addRequestProperty("Connection", "Keep-Alive"); 65 | 66 | if (connection instanceof HttpsURLConnection) { 67 | HttpsURLConnection httpsURLConnection = (HttpsURLConnection) connection; 68 | httpsURLConnection.setHostnameVerifier(DO_NOT_VERIFY); 69 | httpsURLConnection.setSSLSocketFactory(sslContext.getSocketFactory()); 70 | } 71 | 72 | connection.connect(); 73 | 74 | int responseCode = connection.getResponseCode(); 75 | if (responseCode == 200) { 76 | inputStream = connection.getInputStream(); 77 | return inputStream; 78 | } else { 79 | throw new HttpResponseCodeException(responseCode); 80 | } 81 | } 82 | } 83 | 84 | private static SSLContext sslContext; 85 | 86 | private static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { 87 | @SuppressLint("BadHostnameVerifier") 88 | @Override 89 | public boolean verify(String hostname, SSLSession session) { 90 | return true; 91 | } 92 | }; 93 | 94 | static { 95 | // 设置https为全部信任 96 | X509TrustManager xtm = new X509TrustManager() { 97 | @SuppressLint("TrustAllX509TrustManager") 98 | @Override 99 | public void checkClientTrusted(X509Certificate[] chain, String authType) { 100 | } 101 | 102 | @SuppressLint("TrustAllX509TrustManager") 103 | @Override 104 | public void checkServerTrusted(X509Certificate[] chain, String authType) { 105 | } 106 | 107 | @Override 108 | public X509Certificate[] getAcceptedIssuers() { 109 | return new X509Certificate[0]; 110 | } 111 | }; 112 | 113 | 114 | try { 115 | sslContext = SSLContext.getInstance("SSL"); 116 | 117 | sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom()); 118 | 119 | } catch (NoSuchAlgorithmException | KeyManagementException e) { 120 | e.printStackTrace(); 121 | } 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ig/DefaultImageGetter.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ig; 2 | 3 | import android.graphics.Bitmap; 4 | import android.graphics.drawable.BitmapDrawable; 5 | import android.graphics.drawable.Drawable; 6 | import android.widget.TextView; 7 | 8 | import com.zzhoujay.richtext.CacheType; 9 | import com.zzhoujay.richtext.ImageHolder; 10 | import com.zzhoujay.richtext.R; 11 | import com.zzhoujay.richtext.RichTextConfig; 12 | import com.zzhoujay.richtext.cache.BitmapPool; 13 | import com.zzhoujay.richtext.callback.ImageGetter; 14 | import com.zzhoujay.richtext.callback.ImageLoadNotify; 15 | import com.zzhoujay.richtext.drawable.DrawableSizeHolder; 16 | import com.zzhoujay.richtext.drawable.DrawableWrapper; 17 | import com.zzhoujay.richtext.ext.Base64; 18 | import com.zzhoujay.richtext.ext.TextKit; 19 | 20 | import java.io.InputStream; 21 | import java.util.HashSet; 22 | import java.util.Map; 23 | import java.util.WeakHashMap; 24 | import java.util.concurrent.ExecutorService; 25 | import java.util.concurrent.Executors; 26 | import java.util.concurrent.Future; 27 | 28 | import static com.zzhoujay.richtext.ext.Debug.log; 29 | 30 | /** 31 | * Created by zhou on 2016/12/8. 32 | * RichText默认使用的图片加载器 33 | * 支持本地图片,Gif图片,图片缓存,图片缩放等等功能 34 | */ 35 | public class DefaultImageGetter implements ImageGetter, ImageLoadNotify { 36 | 37 | public static final String TAG = "DefaultImageGetter"; 38 | 39 | public static final String GLOBAL_ID = DefaultImageGetter.class.getName(); 40 | 41 | private static final int TASK_TAG = R.id.zhou_default_image_tag_id; 42 | 43 | 44 | private final HashSet tasks; 45 | private final WeakHashMap taskMap; 46 | 47 | private int loadedCount = 0; 48 | private ImageLoadNotify notify; 49 | 50 | public DefaultImageGetter() { 51 | tasks = new HashSet<>(); 52 | taskMap = new WeakHashMap<>(); 53 | } 54 | 55 | private void checkTarget(TextView textView) { 56 | synchronized (DefaultImageGetter.class) { 57 | //noinspection unchecked 58 | HashSet cs = (HashSet) textView.getTag(TASK_TAG); 59 | if (cs != null) { 60 | if (cs == tasks) { 61 | return; 62 | } 63 | //noinspection SpellCheckingInspection 64 | HashSet cancelables = new HashSet<>(cs); 65 | for (Cancelable cancelable : cancelables) { 66 | cancelable.cancel(); 67 | } 68 | cancelables.clear(); 69 | cs.clear(); 70 | } 71 | textView.setTag(TASK_TAG, tasks); 72 | } 73 | } 74 | 75 | @Override 76 | public Drawable getDrawable(final ImageHolder holder, final RichTextConfig config, final TextView textView) { 77 | 78 | checkTarget(textView); 79 | 80 | BitmapPool pool = BitmapPool.getPool(); 81 | String key = holder.getKey(); 82 | DrawableSizeHolder sizeHolder = pool.getSizeHolder(key); 83 | Bitmap bitmap = pool.getBitmap(key); 84 | 85 | final DrawableWrapper drawableWrapper = 86 | config.cacheType.intValue() > CacheType.none.intValue() && sizeHolder != null ? 87 | new DrawableWrapper(sizeHolder) : new DrawableWrapper(holder); 88 | 89 | boolean hasBitmapLocalCache = pool.hasBitmapLocalCache(key); 90 | 91 | Cancelable cancelable = null; 92 | AbstractImageLoader imageLoader = null; 93 | 94 | try { 95 | 96 | if (config.cacheType.intValue() > CacheType.layout.intValue()) { 97 | 98 | if (bitmap != null) { 99 | // 直接从内存中获取 100 | BitmapDrawable bitmapDrawable = new BitmapDrawable(textView.getResources(), bitmap); 101 | bitmapDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); 102 | drawableWrapper.setDrawable(bitmapDrawable); 103 | 104 | drawableWrapper.calculate(); 105 | log(TAG, "cache hit -- memory > " + holder.getSource()); 106 | return drawableWrapper; 107 | } else if (hasBitmapLocalCache) { 108 | // 从缓存中读取 109 | InputStream inputStream = pool.readBitmapFromTemp(key); 110 | InputStreamImageLoader inputStreamImageLoader = new InputStreamImageLoader(holder, config, textView, drawableWrapper, this, inputStream); 111 | Future future = getExecutorService().submit(inputStreamImageLoader); 112 | cancelable = new FutureCancelableWrapper(future); 113 | imageLoader = inputStreamImageLoader; 114 | log(TAG, "cache hit -- local > " + holder.getSource()); 115 | } 116 | } 117 | if (imageLoader == null) { 118 | log(TAG, "cache hit -- none"); 119 | // 无缓存图片,直接加载 120 | if (Base64.isBase64(holder.getSource())) { 121 | // Base64格式图片 122 | Base64ImageLoader base64ImageLoader = new Base64ImageLoader(holder, config, textView, drawableWrapper, this); 123 | Future future = getExecutorService().submit(base64ImageLoader); 124 | cancelable = new FutureCancelableWrapper(future); 125 | imageLoader = base64ImageLoader; 126 | log(TAG, "image load -- base64 > " + holder.getSource()); 127 | } else if (TextKit.isAssetPath(holder.getSource())) { 128 | // Asset文件 129 | AssetsImageLoader assetsImageLoader = new AssetsImageLoader(holder, config, textView, drawableWrapper, this); 130 | Future future = getExecutorService().submit(assetsImageLoader); 131 | cancelable = new FutureCancelableWrapper(future); 132 | imageLoader = assetsImageLoader; 133 | log(TAG, "image load -- asset > " + holder.getSource()); 134 | } else if (TextKit.isLocalPath(holder.getSource())) { 135 | // 本地文件 136 | LocalFileImageLoader localFileImageLoader = new LocalFileImageLoader(holder, config, textView, drawableWrapper, this); 137 | Future future = getExecutorService().submit(localFileImageLoader); 138 | cancelable = new FutureCancelableWrapper(future); 139 | imageLoader = localFileImageLoader; 140 | log(TAG, "image load -- local > " + holder.getSource()); 141 | } else { 142 | // 网络图片 143 | CallbackImageLoader callbackImageLoader = new CallbackImageLoader(holder, config, textView, drawableWrapper, this); 144 | cancelable = ImageDownloaderManager.getImageDownloaderManager().addTask(holder, config.imageDownloader, callbackImageLoader); 145 | imageLoader = callbackImageLoader; 146 | log(TAG, "image load -- remote > " + holder.getSource()); 147 | } 148 | } 149 | } catch (Exception e) { 150 | errorHandle(holder, config, textView, drawableWrapper, e); 151 | } 152 | 153 | if (cancelable != null) { 154 | addTask(cancelable, imageLoader); 155 | } 156 | 157 | return drawableWrapper; 158 | } 159 | 160 | private void errorHandle(ImageHolder holder, RichTextConfig config, TextView textView, DrawableWrapper drawableWrapper, Exception e) { 161 | AbstractImageLoader imageLoader = new AbstractImageLoader(holder, config, textView, drawableWrapper, this, null) { 162 | 163 | }; 164 | imageLoader.onFailure(e); 165 | } 166 | 167 | 168 | private void addTask(Cancelable cancelable, AbstractImageLoader imageLoader) { 169 | synchronized (DefaultImageGetter.class) { 170 | tasks.add(cancelable); 171 | taskMap.put(imageLoader, cancelable); 172 | } 173 | } 174 | 175 | @Override 176 | public void registerImageLoadNotify(ImageLoadNotify imageLoadNotify) { 177 | this.notify = imageLoadNotify; 178 | } 179 | 180 | @Override 181 | public void recycle() { 182 | synchronized (DefaultImageGetter.class) { 183 | for (Cancelable cancelable : tasks) { 184 | cancelable.cancel(); 185 | } 186 | tasks.clear(); 187 | for (Map.Entry imageLoaderCancelableEntry : taskMap.entrySet()) { 188 | imageLoaderCancelableEntry.getKey().recycle(); 189 | } 190 | taskMap.clear(); 191 | } 192 | } 193 | 194 | 195 | @Override 196 | public void done(Object from) { 197 | if (from instanceof AbstractImageLoader) { 198 | AbstractImageLoader imageLoader = ((AbstractImageLoader) from); 199 | synchronized (DefaultImageGetter.class) { 200 | Cancelable cancelable = taskMap.get(imageLoader); 201 | if (cancelable != null) { 202 | tasks.remove(cancelable); 203 | } 204 | taskMap.remove(imageLoader); 205 | loadedCount++; 206 | if (notify != null) { 207 | notify.done(loadedCount); 208 | } 209 | } 210 | } 211 | } 212 | 213 | 214 | private static ExecutorService getExecutorService() { 215 | return ExecutorServiceHolder.EXECUTOR_SERVICE; 216 | } 217 | 218 | 219 | private static class ExecutorServiceHolder { 220 | 221 | private static final ExecutorService EXECUTOR_SERVICE = Executors.newCachedThreadPool(); 222 | 223 | } 224 | 225 | } 226 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ig/FutureCancelableWrapper.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ig; 2 | 3 | import java.util.concurrent.Future; 4 | 5 | /** 6 | * Created by zhou on 2017/2/21. 7 | * FutureCancelableWrapper 8 | */ 9 | class FutureCancelableWrapper implements Cancelable { 10 | 11 | private Future future; 12 | 13 | FutureCancelableWrapper(Future future) { 14 | this.future = future; 15 | } 16 | 17 | @Override 18 | public void cancel() { 19 | if (future != null && !future.isDone() && !future.isCancelled()) { 20 | future.cancel(true); 21 | future = null; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ig/ImageDownloader.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ig; 2 | 3 | import com.zzhoujay.richtext.callback.BitmapStream; 4 | 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | 8 | /** 9 | * Created by zhou on 2017/9/11. 10 | * 图片下载器 11 | */ 12 | 13 | public interface ImageDownloader { 14 | 15 | 16 | /** 17 | * 下载图片并返回流,无需异步 18 | * 19 | * @param source 图片URL 20 | * @return 下载到的图片的输入流 21 | * @throws IOException 抛出的IOException将会被处理 22 | */ 23 | BitmapStream download(String source) throws IOException; 24 | 25 | } 26 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ig/ImageDownloaderManager.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ig; 2 | 3 | import com.zzhoujay.richtext.ImageHolder; 4 | import com.zzhoujay.richtext.cache.BitmapPool; 5 | import com.zzhoujay.richtext.callback.BitmapStream; 6 | import com.zzhoujay.richtext.exceptions.ImageDownloadTaskAddFailureException; 7 | import com.zzhoujay.richtext.exceptions.ImageLoadCancelledException; 8 | import com.zzhoujay.richtext.ext.Debug; 9 | 10 | import java.lang.ref.WeakReference; 11 | import java.util.ArrayList; 12 | import java.util.HashMap; 13 | import java.util.concurrent.ExecutorService; 14 | import java.util.concurrent.Executors; 15 | 16 | /** 17 | * Created by zhou on 2017/10/9. 18 | * 图片下载管理器 19 | */ 20 | 21 | class ImageDownloaderManager { 22 | 23 | 24 | private final HashMap tasks; 25 | 26 | 27 | private ImageDownloaderManager() { 28 | tasks = new HashMap<>(); 29 | } 30 | 31 | 32 | static ImageDownloaderManager getImageDownloaderManager() { 33 | return ImageDownloaderManagerHolder.IMAGE_DOWNLOADER_MANAGER; 34 | } 35 | 36 | 37 | Cancelable addTask(ImageHolder holder, ImageDownloader imageDownloader, CallbackImageLoader callbackImageLoader) { 38 | String key = holder.getKey(); 39 | synchronized (tasks) { 40 | Task task = tasks.get(key); 41 | if (task == null) { 42 | task = new Task(holder.getSource(), key, imageDownloader, IMAGE_READY_CALLBACK); 43 | tasks.put(key, task); 44 | } 45 | return task.exec(getExecutorService(), callbackImageLoader); 46 | } 47 | } 48 | 49 | private final ImageDownloadFinishCallback IMAGE_READY_CALLBACK = new ImageDownloadFinishCallback() { 50 | @Override 51 | public void imageDownloadFinish(String key) { 52 | synchronized (tasks) { 53 | tasks.remove(key); 54 | } 55 | } 56 | }; 57 | 58 | public interface ImageDownloadFinishCallback { 59 | 60 | void imageDownloadFinish(String key); 61 | 62 | } 63 | 64 | 65 | private static class TaskCancelable implements Cancelable { 66 | 67 | private WeakReference taskWeakReference; 68 | private WeakReference callbackImageLoaderWeakReference; 69 | 70 | TaskCancelable(Task task, CallbackImageLoader callbackImageLoader) { 71 | this.taskWeakReference = new WeakReference<>(task); 72 | this.callbackImageLoaderWeakReference = new WeakReference<>(callbackImageLoader); 73 | } 74 | 75 | @Override 76 | public void cancel() { 77 | Task task = taskWeakReference.get(); 78 | if (task != null) { 79 | CallbackImageLoader callbackImageLoader = callbackImageLoaderWeakReference.get(); 80 | if (callbackImageLoader != null) { 81 | task.removeCallback(callbackImageLoader); 82 | callbackImageLoader.onFailure(new ImageLoadCancelledException()); 83 | } 84 | } 85 | } 86 | } 87 | 88 | private static class Task implements Runnable { 89 | 90 | private static final int STATE_INIT = 0; 91 | private static final int STATE_WORK = 1; 92 | private static final int STATE_CALLBACK = 2; 93 | private static final int STATE_FINISHED = 3; 94 | 95 | private final String key; 96 | private final String imageUrl; 97 | private final ImageDownloader imageDownloader; 98 | 99 | private volatile int state; 100 | 101 | private final Object stateLock = new Object(); 102 | 103 | private final ArrayList callbackList; 104 | private final ImageDownloadFinishCallback imageDownloadFinishCallback; 105 | 106 | Task(String imageUrl, String key, ImageDownloader imageDownloader, ImageDownloadFinishCallback imageDownloadFinishCallback) { 107 | this.imageUrl = imageUrl; 108 | this.imageDownloader = imageDownloader; 109 | this.imageDownloadFinishCallback = imageDownloadFinishCallback; 110 | this.state = STATE_INIT; 111 | 112 | this.callbackList = new ArrayList<>(); 113 | 114 | this.key = key; 115 | } 116 | 117 | @Override 118 | public void run() { 119 | 120 | synchronized (stateLock) { 121 | state = STATE_WORK; 122 | } 123 | 124 | Exception exception = null; 125 | 126 | try { 127 | BitmapStream bitmapStream = imageDownloader.download(imageUrl); 128 | BitmapPool.getPool().writeBitmapToTemp(key, bitmapStream.getInputStream()); 129 | bitmapStream.close(); 130 | } catch (Exception e) { 131 | exception = e; 132 | } 133 | 134 | synchronized (stateLock) { 135 | 136 | imageDownloadFinishCallback.imageDownloadFinish(key); 137 | 138 | if (state != STATE_WORK) { 139 | return; 140 | } 141 | 142 | state = STATE_CALLBACK; 143 | 144 | synchronized (callbackList) { 145 | 146 | for (CallbackImageLoader imageLoader : callbackList) { 147 | try { 148 | imageLoader.onImageDownloadFinish(key, exception); 149 | } catch (Throwable e) { 150 | Debug.e(e); 151 | } 152 | } 153 | 154 | } 155 | state = STATE_FINISHED; 156 | } 157 | } 158 | 159 | private void removeCallback(CallbackImageLoader callbackImageLoader) { 160 | synchronized (callbackList) { 161 | callbackList.remove(callbackImageLoader); 162 | } 163 | } 164 | 165 | private Cancelable exec(ExecutorService executorService, CallbackImageLoader callbackImageLoader) { 166 | Cancelable cancelable = null; 167 | synchronized (stateLock) { 168 | if (state == STATE_WORK) { 169 | synchronized (callbackList) { 170 | callbackList.add(callbackImageLoader); 171 | cancelable = new TaskCancelable(this, callbackImageLoader); 172 | } 173 | } 174 | if (state == STATE_INIT) { 175 | state = STATE_WORK; 176 | executorService.submit(this); 177 | 178 | synchronized (callbackList) { 179 | callbackList.add(callbackImageLoader); 180 | cancelable = new TaskCancelable(this, callbackImageLoader); 181 | } 182 | } 183 | } 184 | if (cancelable == null) { 185 | callbackImageLoader.onFailure(new ImageDownloadTaskAddFailureException()); 186 | } 187 | return cancelable; 188 | } 189 | 190 | } 191 | 192 | 193 | private static ExecutorService getExecutorService() { 194 | return ExecutorServiceHolder.EXECUTOR_SERVICE; 195 | } 196 | 197 | 198 | private static class ExecutorServiceHolder { 199 | 200 | private static final ExecutorService EXECUTOR_SERVICE = Executors.newCachedThreadPool(); 201 | 202 | } 203 | 204 | private static class ImageDownloaderManagerHolder { 205 | 206 | private static final ImageDownloaderManager IMAGE_DOWNLOADER_MANAGER = new ImageDownloaderManager(); 207 | 208 | } 209 | 210 | } 211 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ig/ImageLoader.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ig; 2 | 3 | import com.zzhoujay.richtext.callback.Recyclable; 4 | 5 | /** 6 | * Created by zhou on 2016/12/9. 7 | * 图片加载器 8 | */ 9 | interface ImageLoader extends Recyclable { 10 | 11 | /** 12 | * 加载中,设置placeHolder图片 13 | */ 14 | void onLoading(); 15 | 16 | /** 17 | * 图片大小已获取到,进行图片缩放处理 18 | * 19 | * @param width 图片真实宽度 20 | * @param height 图片真实高度 21 | * @return 缩放倍数 22 | */ 23 | int onSizeReady(int width, int height); 24 | 25 | /** 26 | * 图片加载失败,设errorImage 27 | * 28 | * @param e exception 29 | */ 30 | void onFailure(Exception e); 31 | 32 | /** 33 | * 图片加载完成 34 | * 35 | * @param imageWrapper ImageWrapper 36 | */ 37 | void onResourceReady(ImageWrapper imageWrapper); 38 | 39 | } 40 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ig/ImageWrapper.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ig; 2 | 3 | import android.content.res.Resources; 4 | import android.graphics.Bitmap; 5 | import android.graphics.drawable.BitmapDrawable; 6 | import android.graphics.drawable.Drawable; 7 | 8 | import com.zzhoujay.richtext.callback.Recyclable; 9 | import com.zzhoujay.richtext.drawable.GifDrawable; 10 | import com.zzhoujay.richtext.exceptions.ImageWrapperMultiSourceException; 11 | 12 | /** 13 | * Created by zhou on 2017/2/21. 14 | * 抽象的图片类,包含Bitmap静态图的Gif动态图 15 | */ 16 | class ImageWrapper implements Recyclable { 17 | 18 | private final GifDrawable gifDrawable; 19 | private final Bitmap bitmap; 20 | private final int height; 21 | private final int width; 22 | 23 | private ImageWrapper(GifDrawable gifDrawable, Bitmap bitmap) { 24 | this.gifDrawable = gifDrawable; 25 | this.bitmap = bitmap; 26 | if (gifDrawable == null) { 27 | if (bitmap == null) { 28 | throw new ImageWrapperMultiSourceException(); 29 | } else { 30 | height = bitmap.getHeight(); 31 | width = bitmap.getWidth(); 32 | } 33 | } else { 34 | if (bitmap != null) { 35 | throw new ImageWrapperMultiSourceException(); 36 | } else { 37 | height = gifDrawable.getHeight(); 38 | width = gifDrawable.getWidth(); 39 | } 40 | } 41 | } 42 | 43 | boolean isGif() { 44 | return gifDrawable != null; 45 | } 46 | 47 | GifDrawable getAsGif() { 48 | return gifDrawable; 49 | } 50 | 51 | Bitmap getAsBitmap() { 52 | return bitmap; 53 | } 54 | 55 | 56 | int getHeight() { 57 | return height; 58 | } 59 | 60 | int getWidth() { 61 | return width; 62 | } 63 | 64 | Drawable getDrawable(Resources resources) { 65 | if (gifDrawable == null) { 66 | BitmapDrawable bitmapDrawable = new BitmapDrawable(resources, bitmap); 67 | bitmapDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); 68 | return bitmapDrawable; 69 | } else { 70 | return gifDrawable; 71 | } 72 | } 73 | 74 | @Override 75 | public void recycle() { 76 | if (gifDrawable != null) { 77 | gifDrawable.stop(); 78 | } 79 | } 80 | 81 | static ImageWrapper createAsGif(GifDrawable gifDrawable) { 82 | return new ImageWrapper(gifDrawable, null); 83 | } 84 | 85 | static ImageWrapper createAsBitmap(Bitmap bitmap) { 86 | return new ImageWrapper(null, bitmap); 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ig/InputStreamImageLoader.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ig; 2 | 3 | import android.widget.TextView; 4 | 5 | import com.zzhoujay.richtext.ImageHolder; 6 | import com.zzhoujay.richtext.RichTextConfig; 7 | import com.zzhoujay.richtext.callback.ImageLoadNotify; 8 | import com.zzhoujay.richtext.drawable.DrawableWrapper; 9 | import com.zzhoujay.richtext.exceptions.BitmapInputStreamNullPointException; 10 | import com.zzhoujay.richtext.exceptions.ImageDecodeException; 11 | 12 | import java.io.BufferedInputStream; 13 | import java.io.IOException; 14 | import java.io.InputStream; 15 | 16 | /** 17 | * Created by zhou on 2017/10/2. 18 | * 处理流 19 | */ 20 | 21 | class InputStreamImageLoader extends AbstractImageLoader implements Runnable { 22 | 23 | private InputStream inputStream; 24 | 25 | InputStreamImageLoader(ImageHolder holder, RichTextConfig config, TextView textView, DrawableWrapper drawableWrapper, ImageLoadNotify iln, InputStream inputStream) { 26 | super(holder, config, textView, drawableWrapper, iln, SourceDecode.INPUT_STREAM_DECODE); 27 | this.inputStream = inputStream; 28 | } 29 | 30 | @Override 31 | public void run() { 32 | if (inputStream == null) { 33 | onFailure(new BitmapInputStreamNullPointException()); 34 | return; 35 | } 36 | 37 | try { 38 | BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); 39 | doLoadImage(bufferedInputStream); 40 | bufferedInputStream.close(); 41 | inputStream.close(); 42 | } catch (IOException e) { 43 | onFailure(e); 44 | } catch (OutOfMemoryError error) { 45 | onFailure(new ImageDecodeException(error)); 46 | } 47 | 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ig/LocalFileImageLoader.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ig; 2 | 3 | import android.widget.TextView; 4 | 5 | import com.zzhoujay.richtext.ImageHolder; 6 | import com.zzhoujay.richtext.RichTextConfig; 7 | import com.zzhoujay.richtext.callback.ImageLoadNotify; 8 | import com.zzhoujay.richtext.drawable.DrawableWrapper; 9 | import com.zzhoujay.richtext.exceptions.ImageDecodeException; 10 | 11 | /** 12 | * Created by zhou on 2017/2/20. 13 | * 本地图片加载器 14 | */ 15 | 16 | class LocalFileImageLoader extends AbstractImageLoader implements Runnable { 17 | 18 | LocalFileImageLoader(ImageHolder holder, RichTextConfig config, TextView textView, DrawableWrapper drawableWrapper, ImageLoadNotify iln) { 19 | super(holder, config, textView, drawableWrapper, iln, SourceDecode.LOCAL_FILE_SOURCE_DECODE); 20 | } 21 | 22 | @Override 23 | public void run() { 24 | try { 25 | doLoadImage(holder.getSource()); 26 | } catch (Exception e) { 27 | onFailure(new ImageDecodeException(e)); 28 | } catch (OutOfMemoryError error) { 29 | onFailure(new ImageDecodeException(error)); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/ig/SourceDecode.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.ig; 2 | 3 | import android.graphics.Bitmap; 4 | import android.graphics.BitmapFactory; 5 | import android.graphics.Movie; 6 | 7 | import com.zzhoujay.richtext.ImageHolder; 8 | import com.zzhoujay.richtext.drawable.GifDrawable; 9 | import com.zzhoujay.richtext.ext.ImageKit; 10 | 11 | import java.io.BufferedInputStream; 12 | import java.io.IOException; 13 | import java.io.InputStream; 14 | 15 | /** 16 | * Created by zhou on 2017/2/21. 17 | * 图片解析工具 18 | */ 19 | abstract class SourceDecode { 20 | 21 | static SourceDecode BASE64_SOURCE_DECODE = new SourceDecode() { 22 | 23 | @Override 24 | void decodeSize(byte[] bytes, BitmapFactory.Options options) { 25 | BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options); 26 | } 27 | 28 | @Override 29 | public ImageWrapper decodeAsBitmap(byte[] bytes, BitmapFactory.Options options) { 30 | return ImageWrapper.createAsBitmap(BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options)); 31 | } 32 | 33 | @Override 34 | ImageWrapper decodeAsGif(byte[] bytes, BitmapFactory.Options options) { 35 | return ImageWrapper.createAsGif(new GifDrawable(Movie.decodeByteArray(bytes, 0, bytes.length), options.outHeight, options.outWidth)); 36 | } 37 | 38 | @Override 39 | boolean isGif(byte[] bytes, BitmapFactory.Options options) { 40 | return ImageKit.isGif(bytes); 41 | } 42 | }; 43 | 44 | static SourceDecode LOCAL_FILE_SOURCE_DECODE = new SourceDecode() { 45 | 46 | @Override 47 | void decodeSize(String s, BitmapFactory.Options options) { 48 | BitmapFactory.decodeFile(s, options); 49 | } 50 | 51 | @Override 52 | public ImageWrapper decodeAsBitmap(String s, BitmapFactory.Options options) { 53 | return ImageWrapper.createAsBitmap(BitmapFactory.decodeFile(s, options)); 54 | } 55 | 56 | @Override 57 | ImageWrapper decodeAsGif(String s, BitmapFactory.Options options) { 58 | return ImageWrapper.createAsGif(new GifDrawable(Movie.decodeFile(s), options.outHeight, options.outWidth)); 59 | } 60 | 61 | @Override 62 | boolean isGif(String s, BitmapFactory.Options options) { 63 | return ImageKit.isGif(s); 64 | } 65 | }; 66 | 67 | static SourceDecode INPUT_STREAM_DECODE = new SourceDecode() { 68 | 69 | private static final int MARK_POSITION = 1024 * 1024; 70 | 71 | @Override 72 | void decodeSize(InputStream inputStream, BitmapFactory.Options options) { 73 | BufferedInputStream stream; 74 | if (inputStream instanceof BufferedInputStream) { 75 | stream = (BufferedInputStream) inputStream; 76 | } else { 77 | stream = new BufferedInputStream(inputStream); 78 | } 79 | if (options.inJustDecodeBounds) { 80 | stream.mark(MARK_POSITION); 81 | } 82 | BitmapFactory.decodeStream(stream, null, options); 83 | if (options.inJustDecodeBounds) { 84 | try { 85 | stream.reset(); 86 | } catch (IOException e) { 87 | e.printStackTrace(); 88 | } 89 | } 90 | } 91 | 92 | @Override 93 | public ImageWrapper decodeAsBitmap(InputStream inputStream, BitmapFactory.Options options) { 94 | BufferedInputStream stream; 95 | if (inputStream instanceof BufferedInputStream) { 96 | stream = (BufferedInputStream) inputStream; 97 | } else { 98 | stream = new BufferedInputStream(inputStream); 99 | } 100 | if (options.inJustDecodeBounds) { 101 | stream.mark(MARK_POSITION); 102 | } 103 | Bitmap bitmap = BitmapFactory.decodeStream(stream, null, options); 104 | if (options.inJustDecodeBounds) { 105 | try { 106 | stream.reset(); 107 | } catch (IOException e) { 108 | e.printStackTrace(); 109 | } 110 | } 111 | return ImageWrapper.createAsBitmap(bitmap); 112 | } 113 | 114 | @Override 115 | ImageWrapper decodeAsGif(InputStream inputStream, BitmapFactory.Options options) { 116 | return ImageWrapper.createAsGif(new GifDrawable(Movie.decodeStream(inputStream), options.outHeight, options.outWidth)); 117 | } 118 | 119 | @Override 120 | boolean isGif(InputStream inputStream, BitmapFactory.Options options) { 121 | return ImageKit.isGif(inputStream); 122 | } 123 | }; 124 | 125 | ImageWrapper decode(ImageHolder holder, T t, BitmapFactory.Options options) { 126 | if (holder.isAutoPlay() && (holder.isGif() || isGif(t, options))) { 127 | holder.setIsGif(true); 128 | return decodeAsGif(t, options); 129 | } else { 130 | return decodeAsBitmap(t, options); 131 | } 132 | } 133 | 134 | abstract boolean isGif(T t, BitmapFactory.Options options); 135 | 136 | abstract void decodeSize(T t, BitmapFactory.Options options); 137 | 138 | abstract ImageWrapper decodeAsBitmap(T t, BitmapFactory.Options options); 139 | 140 | abstract ImageWrapper decodeAsGif(T t, BitmapFactory.Options options); 141 | 142 | } 143 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/parser/CachedSpannedParser.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.parser; 2 | 3 | import android.graphics.Color; 4 | import android.graphics.drawable.ColorDrawable; 5 | import android.graphics.drawable.Drawable; 6 | import android.text.SpannableStringBuilder; 7 | import android.text.Spanned; 8 | import android.text.style.ClickableSpan; 9 | import android.text.style.ImageSpan; 10 | import android.text.style.URLSpan; 11 | 12 | import com.zzhoujay.richtext.LinkHolder; 13 | import com.zzhoujay.richtext.RichTextConfig; 14 | import com.zzhoujay.richtext.callback.OnImageClickListener; 15 | import com.zzhoujay.richtext.callback.OnImageLongClickListener; 16 | import com.zzhoujay.richtext.spans.ClickableImageSpan; 17 | import com.zzhoujay.richtext.spans.LongClickableURLSpan; 18 | 19 | import java.util.ArrayList; 20 | 21 | /** 22 | * Created by zhou on 2016/12/5. 23 | * CachedSpannedParser 24 | */ 25 | 26 | public class CachedSpannedParser { 27 | 28 | public static class Cached { 29 | } 30 | 31 | public int parse(SpannableStringBuilder ssb, ImageGetterWrapper imageGetter, RichTextConfig config) { 32 | boolean cached = isCached(ssb); 33 | handleClick(ssb, config, cached); 34 | return handleImage(ssb, imageGetter, config, cached); 35 | } 36 | 37 | private void handleClick(SpannableStringBuilder ssb, RichTextConfig config, boolean cached) { 38 | if (cached) { 39 | LongClickableURLSpan[] lcus = ssb.getSpans(0, ssb.length(), LongClickableURLSpan.class); 40 | if (lcus != null && lcus.length > 0) { 41 | for (LongClickableURLSpan lcu : lcus) { 42 | resetLinkSpan(ssb, config, lcu); 43 | } 44 | } 45 | } else { 46 | if (config.clickable >= 0) { 47 | // 处理超链接点击事件 48 | URLSpan[] urlSpans = ssb.getSpans(0, ssb.length(), URLSpan.class); 49 | for (int i = 0, size = urlSpans == null ? 0 : urlSpans.length; i < size; i++) { 50 | resetLinkSpan(ssb, config, urlSpans[i]); 51 | } 52 | } else { 53 | // 移除URLSpan 54 | URLSpan[] urlSpans = ssb.getSpans(0, ssb.length(), URLSpan.class); 55 | for (int i = 0, size = urlSpans == null ? 0 : urlSpans.length; i < size; i++) { 56 | ssb.removeSpan(urlSpans[i]); 57 | } 58 | } 59 | } 60 | } 61 | 62 | private void resetLinkSpan(SpannableStringBuilder ssb, RichTextConfig config, URLSpan urlSpan) { 63 | int start = ssb.getSpanStart(urlSpan); 64 | int end = ssb.getSpanEnd(urlSpan); 65 | ssb.removeSpan(urlSpan); 66 | LinkHolder linkHolder = new LinkHolder(urlSpan.getURL()); 67 | if (config.linkFixCallback != null) { 68 | config.linkFixCallback.fix(linkHolder); 69 | } 70 | LongClickableURLSpan longClickableURLSpan = new LongClickableURLSpan(linkHolder, config.onUrlClickListener, config.onUrlLongClickListener); 71 | ssb.setSpan(longClickableURLSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 72 | } 73 | 74 | private int handleImage(SpannableStringBuilder ssb, ImageGetterWrapper imageGetterWrapper, RichTextConfig config, boolean cached) { 75 | if (cached) { 76 | ClickableImageSpan[] cis = ssb.getSpans(0, ssb.length(), ClickableImageSpan.class); 77 | if (cis != null && cis.length > 0) { 78 | for (ClickableImageSpan ci : cis) { 79 | int start = ssb.getSpanStart(ci); 80 | int end = ssb.getSpanEnd(ci); 81 | ssb.removeSpan(ci); 82 | OnImageClickListener onImageClickListener = null; 83 | OnImageLongClickListener onImageLongClickListener = null; 84 | if (config.clickable > 0) { 85 | onImageClickListener = config.onImageClickListener; 86 | onImageLongClickListener = config.onImageLongClickListener; 87 | } 88 | Drawable drawable = imageGetterWrapper.getDrawable(ci.getSource()); 89 | if (drawable == null) { 90 | drawable = new ColorDrawable(Color.TRANSPARENT); 91 | } 92 | ClickableImageSpan nci = new ClickableImageSpan(drawable, ci, onImageClickListener, onImageLongClickListener); 93 | ssb.setSpan(nci, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 94 | } 95 | return cis.length; 96 | } 97 | } else if (!config.noImage) { 98 | ImageSpan[] iss = ssb.getSpans(0, ssb.length(), ImageSpan.class); 99 | if (iss != null && iss.length > 0) { 100 | ArrayList imageUrls = new ArrayList<>(iss.length); 101 | for (int i = 0; i < iss.length; i++) { 102 | ImageSpan imageSpan = iss[i]; 103 | String imageUrl = imageSpan.getSource(); 104 | imageUrls.add(imageUrl); 105 | 106 | int start = ssb.getSpanStart(imageSpan); 107 | int end = ssb.getSpanEnd(imageSpan); 108 | ClickableSpan[] clickableSpans = ssb.getSpans(start, end, ClickableSpan.class); 109 | if (clickableSpans != null && clickableSpans.length != 0) { 110 | for (ClickableSpan cs : clickableSpans) { 111 | ssb.removeSpan(cs); 112 | } 113 | } 114 | OnImageClickListener onImageClickListener = null; 115 | OnImageLongClickListener onImageLongClickListener = null; 116 | if (config.clickable > 0) { 117 | onImageClickListener = config.onImageClickListener; 118 | onImageLongClickListener = config.onImageLongClickListener; 119 | } 120 | Drawable drawable = imageGetterWrapper.getDrawable(imageUrl); 121 | if (drawable == null) { 122 | drawable = new ColorDrawable(Color.TRANSPARENT); 123 | } 124 | ClickableImageSpan cacheImageSpan = new ClickableImageSpan(drawable, imageUrls, i, onImageClickListener, onImageLongClickListener); 125 | ssb.removeSpan(imageSpan); 126 | ssb.setSpan(cacheImageSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 127 | } 128 | return iss.length; 129 | } 130 | } 131 | return 0; 132 | } 133 | 134 | private boolean isCached(SpannableStringBuilder ssb) { 135 | Cached[] cs = ssb.getSpans(0, ssb.length(), Cached.class); 136 | return cs != null && cs.length > 0; 137 | } 138 | 139 | @SuppressWarnings("unused") 140 | private void clearCachedMark(SpannableStringBuilder ssb) { 141 | Cached[] cs = ssb.getSpans(0, ssb.length(), Cached.class); 142 | if (cs != null && cs.length > 0) { 143 | for (Cached c : cs) { 144 | ssb.removeSpan(c); 145 | } 146 | } 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/parser/Html2SpannedParser.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.parser; 2 | 3 | import android.text.Html; 4 | import android.text.Spanned; 5 | import android.util.Log; 6 | 7 | import java.lang.reflect.Method; 8 | 9 | /** 10 | * Created by zhou on 16-7-27. 11 | * Html2SpannedParser 12 | */ 13 | public class Html2SpannedParser implements SpannedParser { 14 | 15 | private static final String TAG = "Html2SpannedParser"; 16 | 17 | private static final String Z_HTML_CLASS_NAME = "com.zzhoujay.html.Html"; 18 | private static final Method Z_FROM_HTML_METHOD; 19 | 20 | static { 21 | Method fromHtml = null; 22 | try { 23 | fromHtml = Class.forName(Z_HTML_CLASS_NAME).getMethod("fromHtml", String.class, Html.ImageGetter.class, Html.TagHandler.class); 24 | } catch (Exception ignore) { 25 | } 26 | Z_FROM_HTML_METHOD = fromHtml; 27 | } 28 | 29 | private Html.TagHandler tagHandler; 30 | 31 | public Html2SpannedParser(Html.TagHandler tagHandler) { 32 | this.tagHandler = tagHandler; 33 | } 34 | 35 | @Override 36 | public Spanned parse(String source) { 37 | if (Z_FROM_HTML_METHOD != null) { 38 | try { 39 | return (Spanned) Z_FROM_HTML_METHOD.invoke(null, source, null, tagHandler); 40 | } catch (Exception e) { 41 | Log.d(TAG, "Z_FROM_HTML_METHOD invoke failure", e); 42 | } 43 | } 44 | return Html.fromHtml(source, null, tagHandler); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/parser/ImageGetterWrapper.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.parser; 2 | 3 | import android.graphics.drawable.Drawable; 4 | 5 | /** 6 | * Created by zhou on 2016/12/3. 7 | * ImageGetterWrapper 8 | */ 9 | 10 | public interface ImageGetterWrapper { 11 | 12 | Drawable getDrawable(String source); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/parser/Markdown2SpannedParser.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.parser; 2 | 3 | import android.text.Spanned; 4 | import android.widget.TextView; 5 | 6 | import com.zzhoujay.markdown.MarkDown; 7 | 8 | /** 9 | * Created by zhou on 16-7-27. 10 | * Markdown2SpannedParser 11 | */ 12 | public class Markdown2SpannedParser implements SpannedParser { 13 | 14 | private TextView textView; 15 | 16 | public Markdown2SpannedParser(TextView textView) { 17 | this.textView = textView; 18 | } 19 | 20 | @Override 21 | public Spanned parse(String source) { 22 | return MarkDown.fromMarkdown(source, null, textView); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/parser/SpannedParser.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.parser; 2 | 3 | import android.text.Spanned; 4 | 5 | /** 6 | * Created by zhou on 16-7-27. 7 | * SpannedParser 8 | */ 9 | public interface SpannedParser { 10 | 11 | Spanned parse(String source); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/spans/Clickable.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.spans; 2 | 3 | import android.view.View; 4 | 5 | /** 6 | * Created by zhou on 2016/11/17. 7 | * Clickable 8 | */ 9 | @SuppressWarnings("WeakerAccess") 10 | public interface Clickable { 11 | 12 | void onClick(View widget); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/spans/ClickableImageSpan.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.spans; 2 | 3 | import android.graphics.Canvas; 4 | import android.graphics.Paint; 5 | import android.graphics.Rect; 6 | import android.graphics.drawable.Drawable; 7 | import android.text.style.ImageSpan; 8 | import android.view.View; 9 | 10 | import com.zzhoujay.richtext.callback.OnImageClickListener; 11 | import com.zzhoujay.richtext.callback.OnImageLongClickListener; 12 | 13 | import java.util.List; 14 | 15 | /** 16 | * Created by zhou on 2016/11/17. 17 | * ClickableImageSpan 支持点击的ImageSpan 18 | */ 19 | public class ClickableImageSpan extends ImageSpan implements LongClickableSpan { 20 | 21 | private float x; 22 | private final int position; 23 | private final List imageUrls; 24 | private final OnImageLongClickListener onImageLongClickListener; 25 | private final OnImageClickListener onImageClickListener; 26 | 27 | public ClickableImageSpan(Drawable drawable, ClickableImageSpan clickableImageSpan, OnImageClickListener onImageClickListener, OnImageLongClickListener onImageLongClickListener) { 28 | super(drawable, clickableImageSpan.getSource()); 29 | this.imageUrls = clickableImageSpan.imageUrls; 30 | this.position = clickableImageSpan.position; 31 | this.onImageClickListener = onImageClickListener; 32 | this.onImageLongClickListener = onImageLongClickListener; 33 | } 34 | 35 | public ClickableImageSpan(Drawable drawable, List imageUrls, int position, OnImageClickListener onImageClickListener, OnImageLongClickListener onImageLongClickListener) { 36 | super(drawable, imageUrls.get(position)); 37 | this.imageUrls = imageUrls; 38 | this.position = position; 39 | this.onImageClickListener = onImageClickListener; 40 | this.onImageLongClickListener = onImageLongClickListener; 41 | } 42 | 43 | 44 | @Override 45 | public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) { 46 | super.draw(canvas, text, start, end, x, top, y, bottom, paint); 47 | this.x = x; 48 | } 49 | 50 | public boolean clicked(int position) { 51 | Drawable drawable = getDrawable(); 52 | if (drawable != null) { 53 | Rect rect = drawable.getBounds(); 54 | return position <= rect.right + x && position >= rect.left + x; 55 | } 56 | return false; 57 | } 58 | 59 | 60 | @Override 61 | public void onClick(View widget) { 62 | if (onImageClickListener != null) { 63 | onImageClickListener.imageClicked(imageUrls, position); 64 | } 65 | } 66 | 67 | @Override 68 | public boolean onLongClick(View widget) { 69 | return onImageLongClickListener != null && onImageLongClickListener.imageLongClicked(imageUrls, position); 70 | } 71 | 72 | public ClickableImageSpan copy() { 73 | return new ClickableImageSpan(null, imageUrls, position, null, null); 74 | } 75 | 76 | public String getSource() { 77 | return imageUrls.get(position); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/spans/LongClickable.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.spans; 2 | 3 | import android.view.View; 4 | 5 | /** 6 | * Created by zhou on 16-8-4. 7 | * LongClickable 8 | */ 9 | @SuppressWarnings("WeakerAccess") 10 | public interface LongClickable { 11 | /** 12 | * 长按点击时间 13 | * 14 | * @param widget  view 15 | * @return true:已处理,false:交由onClick处理 16 | */ 17 | boolean onLongClick(View widget); 18 | } 19 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/spans/LongClickableSpan.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.spans; 2 | 3 | /** 4 | * Created by zhou on 16-8-4. 5 | * LongClickableSpan 6 | */ 7 | public interface LongClickableSpan extends Clickable, LongClickable { 8 | } 9 | -------------------------------------------------------------------------------- /richtext/src/main/java/com/zzhoujay/richtext/spans/LongClickableURLSpan.java: -------------------------------------------------------------------------------- 1 | package com.zzhoujay.richtext.spans; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.text.TextPaint; 5 | import android.text.style.URLSpan; 6 | import android.view.View; 7 | 8 | import com.zzhoujay.richtext.LinkHolder; 9 | import com.zzhoujay.richtext.callback.OnUrlClickListener; 10 | import com.zzhoujay.richtext.callback.OnUrlLongClickListener; 11 | 12 | /** 13 | * Created by zhou on 16-5-28. 14 | * LongClickableURLSpan 15 | */ 16 | @SuppressLint("ParcelCreator") 17 | public class LongClickableURLSpan extends URLSpan implements LongClickableSpan { 18 | 19 | 20 | private final OnUrlClickListener onUrlClickListener; 21 | private final OnUrlLongClickListener onUrlLongClickListener; 22 | private final LinkHolder linkHolder; 23 | 24 | @SuppressWarnings("unused") 25 | public LongClickableURLSpan(LinkHolder linkHolder) { 26 | this(linkHolder, null, null); 27 | } 28 | 29 | public LongClickableURLSpan(LinkHolder linkHolder, OnUrlClickListener onUrlClickListener, OnUrlLongClickListener onUrlLongClickListener) { 30 | super(linkHolder.getUrl()); 31 | this.onUrlClickListener = onUrlClickListener; 32 | this.onUrlLongClickListener = onUrlLongClickListener; 33 | this.linkHolder = linkHolder; 34 | } 35 | 36 | @Override 37 | public void updateDrawState(TextPaint ds) { 38 | ds.setColor(linkHolder.getColor()); 39 | ds.setUnderlineText(linkHolder.isUnderLine()); 40 | } 41 | 42 | @Override 43 | public void onClick(View widget) { 44 | if (onUrlClickListener != null && onUrlClickListener.urlClicked(getURL())) { 45 | return; 46 | } 47 | super.onClick(widget); 48 | } 49 | 50 | @Override 51 | public boolean onLongClick(View widget) { 52 | return onUrlLongClickListener != null && onUrlLongClickListener.urlLongClick(getURL()); 53 | } 54 | 55 | public LongClickableURLSpan copy() { 56 | return new LongClickableURLSpan(linkHolder, null, null); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /richtext/src/main/res/values/zhou_ids.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':richtext', ':okhttpimagedownloader' 2 | --------------------------------------------------------------------------------