├── .gitignore ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── zjy │ │ └── androidpdfhelper │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── assets │ │ └── test.pdf │ ├── java │ │ └── com │ │ │ └── zjy │ │ │ └── androidpdfhelper │ │ │ ├── CustomControllerBar.java │ │ │ ├── CustomPdfViewActivity.java │ │ │ └── MainActivity.java │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ ├── activity_custom_pdf_view.xml │ │ └── activity_main.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── zjy │ └── androidpdfhelper │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── image └── pdf_preview_1.png ├── pdfview ├── .gitignore ├── build.gradle ├── consumer-rules.pro ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── zjy │ │ └── pdfview │ │ ├── PdfPreviewUtils.java │ │ ├── PdfRendererActivity.java │ │ ├── PdfView.java │ │ ├── adapter │ │ └── PdfPageAdapter.java │ │ ├── constants │ │ └── Constants.java │ │ ├── download │ │ ├── DownloadManager.java │ │ ├── DownloadResultBroadcast.java │ │ ├── DownloadService.java │ │ └── IDownloadCallback.java │ │ ├── utils │ │ ├── FileUtils.java │ │ ├── PdfLog.java │ │ ├── ReflectUtils.java │ │ └── layoutmanager │ │ │ ├── MyPagerSnapHelper.java │ │ │ ├── PageLayoutManager.java │ │ │ └── PagerChangedListener.java │ │ └── widget │ │ ├── AbsControllerBar.java │ │ ├── IPDFController.java │ │ ├── LoadingView.java │ │ ├── PDFControllerBar.java │ │ ├── PdfLoadingLayout.java │ │ ├── PdfRecyclerView.java │ │ ├── ScaleImageView.java │ │ └── ScrollSlider.java │ └── res │ ├── drawable-xxhdpi │ ├── ic_top_arrow.png │ └── pdf_ic_left_arrow.png │ ├── drawable │ └── bg_operate_btn.xml │ ├── layout │ ├── activity_pdfrenderer.xml │ ├── layout_page_item.xml │ ├── layout_pdf_loading.xml │ └── layout_pdf_view.xml │ ├── values-v21 │ └── styles.xml │ ├── values-zh-rCN │ └── strings.xml │ └── values │ ├── attrs.xml │ ├── strings.xml │ └── styles.xml └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | .DS_Store 11 | /build 12 | /captures 13 | .externalNativeBuild 14 | .cxx 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AndroidPdfHelper [![](https://jitpack.io/v/GitHubZJY/AndroidPdfHelper.svg)](https://jitpack.io/#GitHubZJY/AndroidPdfHelper) 2 | 一个基于Android PdfRenderer实现的PDF预览组件,支持对PDF文件的分页切换、放大缩小、拖动定位等操作。
3 | A PDF preview component based on Android pdfRenderer, which supports paging switching, zooming in and out, dragging and positioning of PDF files. 4 | 5 | ## 特性 6 | 1. 基于PdfRenderer实现,不同于其它第三方库,占用包体小
7 | 2. 支持PDF文件的上下页切换
8 | 3. 支持PDF单页的放大缩小查看
9 | 4. 支持设置文件预览清晰度
10 | 5. 支持自定义控制栏样式
11 | 6. 支持AndroidX
12 | 13 | ## 效果预览 14 | ![](https://github.com/GitHubZJY/AndroidPdfHelper/blob/master/image/pdf_preview_1.png) 15 | 16 | ## 如何使用 17 | 在项目根目录的build.gradle添加: 18 | ``` 19 | allprojects { 20 | repositories { 21 | ... 22 | maven { url 'https://jitpack.io' } 23 | } 24 | } 25 | ``` 26 | 27 | 在项目的build.gradle添加如下依赖: 28 | ``` 29 | implementation 'com.github.GitHubZJY:AndroidPdfHelper:v1.0.0' 30 | ``` 31 | 32 | ### 1.以View的方式调用 33 | 34 | ```xml 35 | 39 | 40 | 41 | ``` 42 | 43 | 在代码中初始化PdfView 44 | ```java 45 | PdfView pdfView = findViewById(R.id.pdf_view); 46 | ``` 47 |   48 | 预览在线PDF文件: 49 | ```java 50 | pdfView.loadPdf("http://.....xx.pdf"); 51 | ``` 52 |   53 | 预览asset文件: 54 | ```java 55 | pdfView.loadPdf("file:///android_asset/test.pdf"); 56 | ``` 57 |   58 | 自定义预览操作条: 59 | 首先继承于 `AbsControllerBar`, 重写 `getView` 方法返回自定义的视图 60 | ``` 61 | public class CustomControllerBar extends AbsControllerBar { 62 | public View getView() { 63 | //... 64 | } 65 | } 66 | ``` 67 | 通过 `setPDFController` 设置自定义的Controller即可 68 | ```java 69 | CustomControllerBar controllerBar = new CustomControllerBar(this); 70 | pdfView.setPDFController(controllerBar); 71 | ``` 72 | 73 | ### 2.以页面方式调起 74 | 以页面的形式,自带了默认的顶部标题栏,适配Android 5.0以下,会自动下载并调用浏览器打开 75 | 预览在线PDF文件: 76 | ```java 77 | PdfPreviewUtils.previewPdf(context, "http://.....xx.pdf"); 78 | ``` 79 |   80 | 预览asset文件: 81 | ```java 82 | PdfPreviewUtils.previewPdf(context, "file:///android_asset/test.pdf"); 83 | ``` 84 | 85 |   86 | ### 3.设置预览清晰度. 87 | ```xml 88 | 93 | 94 | 95 | ``` 96 | 通过设置 `quality` 属性即可,目前一共有低、中、高三种清晰度,如下: 97 | >高清晰度:**high**
98 | 中等清晰度:**medium**
99 | 低清晰度:**low** 100 | 101 |   102 | ## 其他 103 | 本库基于PdfRenderer实现,目前支持在线或本地pdf文件预览,另外还支持侧边导航滑块,可定位到任意一页,双指拖拽或双击可对单页进行放大缩小控制。 104 | 由于PdfRenderer提供的支持有限,主要还是在于预览在线和本地PDF文件,但优点在于其体积小,后续会继续更新,提供更多PDF预览方面的功能,欢迎issue和star~ 105 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 32 5 | 6 | defaultConfig { 7 | applicationId "com.zjy.androidpdfhelper" 8 | minSdkVersion 19 9 | versionCode 1 10 | versionName "1.0" 11 | 12 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 13 | } 14 | 15 | buildTypes { 16 | release { 17 | minifyEnabled false 18 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 19 | } 20 | } 21 | compileOptions { 22 | sourceCompatibility JavaVersion.VERSION_1_8 23 | targetCompatibility JavaVersion.VERSION_1_8 24 | } 25 | } 26 | 27 | dependencies { 28 | implementation project(':pdfview') 29 | implementation 'androidx.core:core-ktx:1.8.0' 30 | implementation 'androidx.appcompat:appcompat:1.5.0' 31 | implementation 'androidx.constraintlayout:constraintlayout:2.1.4' 32 | testImplementation 'junit:junit:4.13.2' 33 | androidTestImplementation 'androidx.test.ext:junit:1.1.3' 34 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' 35 | 36 | } -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /app/src/androidTest/java/com/zjy/androidpdfhelper/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.zjy.androidpdfhelper; 2 | 3 | import android.content.Context; 4 | 5 | import androidx.test.platform.app.InstrumentationRegistry; 6 | import androidx.test.ext.junit.runners.AndroidJUnit4; 7 | 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * Instrumented test, which will execute on an Android device. 15 | * 16 | * @see Testing documentation 17 | */ 18 | @RunWith(AndroidJUnit4.class) 19 | public class ExampleInstrumentedTest { 20 | @Test 21 | public void useAppContext() { 22 | // Context of the app under test. 23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); 24 | assertEquals("com.zjy.androidpdfhelper", appContext.getPackageName()); 25 | } 26 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /app/src/main/assets/test.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GitHubZJY/AndroidPdfHelper/d561237e9187a783769f7027462bb1a3217e116d/app/src/main/assets/test.pdf -------------------------------------------------------------------------------- /app/src/main/java/com/zjy/androidpdfhelper/CustomControllerBar.java: -------------------------------------------------------------------------------- 1 | package com.zjy.androidpdfhelper; 2 | 3 | import static android.view.Gravity.CENTER; 4 | import static android.widget.LinearLayout.HORIZONTAL; 5 | 6 | import android.content.Context; 7 | import android.graphics.Color; 8 | import android.graphics.Typeface; 9 | import android.os.Build; 10 | import android.util.AttributeSet; 11 | import android.util.TypedValue; 12 | import android.view.View; 13 | import android.view.ViewGroup; 14 | import android.widget.Button; 15 | import android.widget.LinearLayout; 16 | import android.widget.TextView; 17 | 18 | import androidx.annotation.Nullable; 19 | 20 | import com.zjy.pdfview.R; 21 | import com.zjy.pdfview.widget.AbsControllerBar; 22 | 23 | /** 24 | * Date: 2022/2/10 25 | * Author: Yang 26 | * Describe: 自定义PDF控制栏视图 27 | */ 28 | public class CustomControllerBar extends AbsControllerBar implements View.OnClickListener { 29 | 30 | private Button previousBtn, nextBtn; 31 | private TextView pageIndexTv; 32 | 33 | public CustomControllerBar(Context context) { 34 | this(context, null); 35 | } 36 | 37 | public CustomControllerBar(Context context, @Nullable AttributeSet attrs) { 38 | this(context, attrs, 0); 39 | } 40 | 41 | public CustomControllerBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 42 | super(context, attrs, defStyleAttr); 43 | } 44 | 45 | @Override 46 | public View getView() { 47 | LinearLayout rootView= new LinearLayout(getContext()); 48 | rootView.setOrientation(HORIZONTAL); 49 | rootView.setGravity(CENTER); 50 | setBackgroundColor(Color.WHITE); 51 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 52 | setElevation(dip2px(getContext(), 8)); 53 | } 54 | 55 | previousBtn = new Button(getContext()); 56 | previousBtn.setBackgroundResource(R.drawable.bg_operate_btn); 57 | previousBtn.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14); 58 | previousBtn.setText("Previous"); 59 | rootView.addView(previousBtn, new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, dip2px(getContext(), 36))); 60 | 61 | pageIndexTv = new TextView(getContext()); 62 | pageIndexTv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15); 63 | pageIndexTv.setPadding(dip2px(getContext(), 16), 0, dip2px(getContext(), 16), 0); 64 | rootView.addView(pageIndexTv, new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 65 | pageIndexTv.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); 66 | pageIndexTv.setText("1/1"); 67 | 68 | nextBtn = new Button(getContext()); 69 | nextBtn.setBackgroundResource(R.drawable.bg_operate_btn); 70 | nextBtn.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14); 71 | nextBtn.setText("Next"); 72 | rootView.addView(nextBtn, new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, dip2px(getContext(), 36))); 73 | 74 | previousBtn.setOnClickListener(this); 75 | nextBtn.setOnClickListener(this); 76 | return rootView; 77 | } 78 | 79 | @Override 80 | public void onClick(View view) { 81 | if (view == previousBtn) { 82 | clickPrevious(); 83 | } else if (view == nextBtn) { 84 | clickNext(); 85 | } 86 | } 87 | 88 | @Override 89 | public void setPreviousText(String previousText) { 90 | if (previousBtn != null && previousText != null) { 91 | previousBtn.setText(previousText); 92 | } 93 | } 94 | 95 | @Override 96 | public void setNextText(String nextText) { 97 | if (nextBtn != null && nextText != null) { 98 | nextBtn.setText(nextText); 99 | } 100 | } 101 | 102 | private static int dip2px(Context context, float dpValue) { 103 | final float scale = context.getResources().getDisplayMetrics().density; 104 | return (int) (dpValue * scale + 0.5f); 105 | } 106 | 107 | @Override 108 | public void setPageIndexText(String text) { 109 | if (pageIndexTv != null && text != null) { 110 | pageIndexTv.setText(text); 111 | } 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /app/src/main/java/com/zjy/androidpdfhelper/CustomPdfViewActivity.java: -------------------------------------------------------------------------------- 1 | package com.zjy.androidpdfhelper; 2 | 3 | import android.app.Activity; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.os.Bundle; 7 | import android.view.View; 8 | import android.widget.ImageView; 9 | import com.zjy.pdfview.PdfView; 10 | 11 | /** 12 | * Date: 2022/2/10 13 | * Author: Yang 14 | * Describe: 自定义PDF视图 15 | */ 16 | public class CustomPdfViewActivity extends Activity { 17 | 18 | private static final String PDF_URL_KEY = "PDF_URL_KEY"; 19 | 20 | PdfView pdfView; 21 | ImageView backIv; 22 | 23 | public static void startPreview(Context context, String url) { 24 | Intent intent = new Intent(context, CustomPdfViewActivity.class); 25 | intent.putExtra(PDF_URL_KEY, url); 26 | context.startActivity(intent); 27 | } 28 | 29 | @Override 30 | protected void onCreate(Bundle savedInstanceState) { 31 | super.onCreate(savedInstanceState); 32 | setContentView(R.layout.activity_custom_pdf_view); 33 | 34 | backIv = findViewById(com.zjy.pdfview.R.id.back_iv); 35 | backIv.setOnClickListener(new View.OnClickListener() { 36 | @Override 37 | public void onClick(View v) { 38 | finish(); 39 | } 40 | }); 41 | 42 | String url = getIntent().getStringExtra(PDF_URL_KEY); 43 | pdfView = findViewById(com.zjy.pdfview.R.id.pdf_view); 44 | pdfView.loadPdf(url); 45 | CustomControllerBar controllerBar = new CustomControllerBar(this); 46 | pdfView.setPDFController(controllerBar); 47 | } 48 | 49 | 50 | @Override 51 | protected void onDestroy() { 52 | super.onDestroy(); 53 | pdfView.release(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /app/src/main/java/com/zjy/androidpdfhelper/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.zjy.androidpdfhelper; 2 | 3 | import androidx.appcompat.app.AppCompatActivity; 4 | 5 | import android.os.Bundle; 6 | import android.util.Log; 7 | 8 | import com.zjy.pdfview.PdfPreviewUtils; 9 | 10 | public class MainActivity extends AppCompatActivity { 11 | 12 | @Override 13 | protected void onCreate(Bundle savedInstanceState) { 14 | super.onCreate(savedInstanceState); 15 | setContentView(R.layout.activity_main); 16 | 17 | //CustomPdfViewActivity.startPreview(this, "file:///android_asset/test.pdf"); 18 | 19 | PdfPreviewUtils.previewPdf(this, "file:///android_asset/test.pdf"); 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_custom_pdf_view.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 17 | 29 | 38 | 39 | 40 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 17 | 18 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GitHubZJY/AndroidPdfHelper/d561237e9187a783769f7027462bb1a3217e116d/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GitHubZJY/AndroidPdfHelper/d561237e9187a783769f7027462bb1a3217e116d/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GitHubZJY/AndroidPdfHelper/d561237e9187a783769f7027462bb1a3217e116d/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GitHubZJY/AndroidPdfHelper/d561237e9187a783769f7027462bb1a3217e116d/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GitHubZJY/AndroidPdfHelper/d561237e9187a783769f7027462bb1a3217e116d/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GitHubZJY/AndroidPdfHelper/d561237e9187a783769f7027462bb1a3217e116d/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GitHubZJY/AndroidPdfHelper/d561237e9187a783769f7027462bb1a3217e116d/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GitHubZJY/AndroidPdfHelper/d561237e9187a783769f7027462bb1a3217e116d/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GitHubZJY/AndroidPdfHelper/d561237e9187a783769f7027462bb1a3217e116d/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GitHubZJY/AndroidPdfHelper/d561237e9187a783769f7027462bb1a3217e116d/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #6200EE 4 | #3700B3 5 | #03DAC5 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | AndroidPdfHelper 3 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/test/java/com/zjy/androidpdfhelper/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.zjy.androidpdfhelper; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 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() { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | buildscript { 3 | repositories { 4 | google() 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath "com.android.tools.build:gradle:7.2.2" 9 | 10 | // NOTE: Do not place your application dependencies here; they belong 11 | // in the individual module build.gradle files 12 | } 13 | } 14 | 15 | allprojects { 16 | repositories { 17 | google() 18 | jcenter() 19 | } 20 | } 21 | 22 | task clean(type: Delete) { 23 | delete rootProject.buildDir 24 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app"s APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GitHubZJY/AndroidPdfHelper/d561237e9187a783769f7027462bb1a3217e116d/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sun Jan 31 17:10:20 CST 2021 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 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 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /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 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /image/pdf_preview_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GitHubZJY/AndroidPdfHelper/d561237e9187a783769f7027462bb1a3217e116d/image/pdf_preview_1.png -------------------------------------------------------------------------------- /pdfview/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /pdfview/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | 4 | android { 5 | compileSdkVersion 32 6 | 7 | defaultConfig { 8 | minSdkVersion 19 9 | versionCode 1 10 | versionName "1.0" 11 | 12 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 13 | } 14 | 15 | buildTypes { 16 | release { 17 | minifyEnabled false 18 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 19 | } 20 | } 21 | compileOptions { 22 | sourceCompatibility JavaVersion.VERSION_1_8 23 | targetCompatibility JavaVersion.VERSION_1_8 24 | } 25 | } 26 | 27 | dependencies { 28 | 29 | implementation 'androidx.core:core-ktx:1.8.0' 30 | implementation 'androidx.appcompat:appcompat:1.5.0' 31 | implementation 'com.google.android.material:material:1.6.1' 32 | implementation 'androidx.constraintlayout:constraintlayout:2.1.4' 33 | implementation 'androidx.recyclerview:recyclerview:1.2.1' 34 | implementation 'com.squareup.okhttp3:okhttp:4.9.3' 35 | } -------------------------------------------------------------------------------- /pdfview/consumer-rules.pro: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GitHubZJY/AndroidPdfHelper/d561237e9187a783769f7027462bb1a3217e116d/pdfview/consumer-rules.pro -------------------------------------------------------------------------------- /pdfview/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /pdfview/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/PdfPreviewUtils.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview; 2 | 3 | import android.content.Context; 4 | import android.content.Intent; 5 | import android.net.Uri; 6 | import android.os.Build; 7 | import android.widget.Toast; 8 | 9 | import com.zjy.pdfview.download.DownloadManager; 10 | import com.zjy.pdfview.download.IDownloadCallback; 11 | 12 | /** 13 | * Date: 2021/1/28 14 | * Author: Yang 15 | * Describe: 16 | */ 17 | public class PdfPreviewUtils { 18 | 19 | public static void previewPdf(final Context context, String url) { 20 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 21 | PdfRendererActivity.startPreview(context, url); 22 | } else { 23 | DownloadManager downloadManager = new DownloadManager(new IDownloadCallback() { 24 | @Override 25 | public void downloadSuccess(String path) { 26 | 27 | } 28 | 29 | @Override 30 | public void downloadFail() { 31 | 32 | } 33 | 34 | @Override 35 | public void downloadComplete(String path) { 36 | Uri uri = Uri.parse("file://" + path); 37 | Intent intent = new Intent(); 38 | intent.setAction(Intent.ACTION_VIEW); 39 | intent.setData(uri); 40 | if (intent.resolveActivity(context.getPackageManager()) != null) { 41 | context.startActivity(Intent.createChooser(intent, "请选择浏览器打开")); 42 | } else { 43 | Toast.makeText(context, 44 | "没有可用的浏览器", 45 | Toast.LENGTH_SHORT).show(); 46 | } 47 | } 48 | }); 49 | downloadManager.downloadFile(context, url); 50 | 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/PdfRendererActivity.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview; 2 | 3 | import android.app.Activity; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.os.Build; 7 | import android.os.Bundle; 8 | import android.view.View; 9 | import android.widget.ImageView; 10 | 11 | import androidx.annotation.RequiresApi; 12 | 13 | /** 14 | * Date: 2021/1/26 15 | * Author: Yang 16 | * Describe: 17 | */ 18 | @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) 19 | public class PdfRendererActivity extends Activity { 20 | 21 | private static final String PDF_URL_KEY = "PDF_URL_KEY"; 22 | 23 | PdfView pdfView; 24 | ImageView backIv; 25 | 26 | public static void startPreview(Context context, String url) { 27 | Intent intent = new Intent(context, PdfRendererActivity.class); 28 | intent.putExtra(PDF_URL_KEY, url); 29 | context.startActivity(intent); 30 | } 31 | 32 | @Override 33 | protected void onCreate(Bundle savedInstanceState) { 34 | super.onCreate(savedInstanceState); 35 | setContentView(R.layout.activity_pdfrenderer); 36 | 37 | backIv = findViewById(R.id.back_iv); 38 | backIv.setOnClickListener(new View.OnClickListener() { 39 | @Override 40 | public void onClick(View v) { 41 | finish(); 42 | } 43 | }); 44 | 45 | String url = getIntent().getStringExtra(PDF_URL_KEY); 46 | pdfView = findViewById(R.id.pdf_view); 47 | pdfView.loadPdf(url); 48 | pdfView.setPreviousText(getResources().getString(R.string.previous)); 49 | pdfView.setNextText(getResources().getString(R.string.next)); 50 | } 51 | 52 | 53 | @Override 54 | protected void onDestroy() { 55 | super.onDestroy(); 56 | pdfView.release(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/PdfView.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview; 2 | 3 | import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; 4 | import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; 5 | import static com.zjy.pdfview.constants.Constants.DOWNLOAD_ACTION; 6 | import static com.zjy.pdfview.download.DownloadService.DOWNLOAD_URL_KEY; 7 | 8 | import android.content.Context; 9 | import android.content.Intent; 10 | import android.content.IntentFilter; 11 | import android.content.res.TypedArray; 12 | import android.graphics.Bitmap; 13 | import android.graphics.pdf.PdfRenderer; 14 | import android.os.AsyncTask; 15 | import android.os.Build; 16 | import android.os.ParcelFileDescriptor; 17 | import android.text.TextUtils; 18 | import android.util.AttributeSet; 19 | import android.view.LayoutInflater; 20 | import android.view.ViewGroup; 21 | import android.widget.FrameLayout; 22 | 23 | import androidx.annotation.NonNull; 24 | import androidx.annotation.Nullable; 25 | import androidx.annotation.RequiresApi; 26 | import androidx.recyclerview.widget.RecyclerView; 27 | 28 | import com.zjy.pdfview.adapter.PdfPageAdapter; 29 | import com.zjy.pdfview.download.DownloadResultBroadcast; 30 | import com.zjy.pdfview.download.DownloadService; 31 | import com.zjy.pdfview.download.IDownloadCallback; 32 | import com.zjy.pdfview.utils.FileUtils; 33 | import com.zjy.pdfview.utils.PdfLog; 34 | import com.zjy.pdfview.utils.layoutmanager.PageLayoutManager; 35 | import com.zjy.pdfview.utils.layoutmanager.PagerChangedListener; 36 | import com.zjy.pdfview.widget.AbsControllerBar; 37 | import com.zjy.pdfview.widget.IPDFController; 38 | import com.zjy.pdfview.widget.PdfLoadingLayout; 39 | import com.zjy.pdfview.widget.ScrollSlider; 40 | 41 | import java.io.File; 42 | import java.io.IOException; 43 | import java.util.ArrayList; 44 | import java.util.List; 45 | 46 | /** 47 | * Date: 2021/1/27 48 | * Author: Yang 49 | * Describe: 50 | */ 51 | @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) 52 | public class PdfView extends FrameLayout implements IDownloadCallback, IPDFController.OperateListener { 53 | 54 | private ViewGroup rootView; 55 | private FrameLayout controllerContainer; 56 | private RecyclerView contentRv; 57 | private PdfLoadingLayout loadingLayout; 58 | private ScrollSlider scrollSlider; 59 | 60 | /** 61 | * page count of pdf file 62 | */ 63 | private int pageCount; 64 | /** 65 | * index of current page 66 | */ 67 | private int currentIndex; 68 | /** 69 | * quality of preview 70 | */ 71 | private int quality; 72 | 73 | private String pdfLocalPath; 74 | private String pdfUrl; 75 | 76 | private List pageList; 77 | 78 | private PdfRenderer pdfRenderer; 79 | private PdfRenderer.Page curPdfPage; 80 | private ParcelFileDescriptor parcelFileDescriptor; 81 | 82 | private PdfPageAdapter pageAdapter; 83 | private PageLayoutManager pageLayoutManager; 84 | private Intent serviceIntent; 85 | private RenderTask renderTask; 86 | 87 | private boolean hasRenderFinish; 88 | 89 | public PdfView(@NonNull Context context) { 90 | this(context, null); 91 | } 92 | 93 | public PdfView(@NonNull Context context, @Nullable AttributeSet attrs) { 94 | this(context, attrs, 0); 95 | } 96 | 97 | public PdfView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 98 | super(context, attrs, defStyleAttr); 99 | handleStyleable(context, attrs); 100 | init(); 101 | } 102 | 103 | private void handleStyleable(Context context, AttributeSet attrs) { 104 | TypedArray ta = context.getTheme().obtainStyledAttributes(attrs, R.styleable.PdfView, 0, 0); 105 | try { 106 | quality = ta.getInteger(R.styleable.PdfView_quality, 3); 107 | } catch (Exception e) { 108 | e.printStackTrace(); 109 | } finally { 110 | ta.recycle(); 111 | } 112 | } 113 | 114 | 115 | private void init() { 116 | registerResultBroadcast(); 117 | 118 | LayoutInflater.from(getContext()).inflate(R.layout.layout_pdf_view, this); 119 | rootView = findViewById(R.id.pdf_root_view); 120 | controllerContainer = findViewById(R.id.button_group); 121 | loadingLayout = findViewById(R.id.loading_layout); 122 | contentRv = findViewById(R.id.content_rv); 123 | scrollSlider = findViewById(R.id.scroll_slider); 124 | 125 | pageLayoutManager = new PageLayoutManager(getContext(), PageLayoutManager.VERTICAL); 126 | pageLayoutManager.setOnPagerChangeListener(new PagerChangedListener() { 127 | @Override 128 | public void onInitComplete() { 129 | 130 | } 131 | 132 | @Override 133 | public void onPageRelease(boolean isNext, int position) { 134 | scrollToPosition(); 135 | } 136 | 137 | @Override 138 | public void onPageSelected(int position, boolean isBottom) { 139 | 140 | } 141 | }); 142 | contentRv.setLayoutManager(pageLayoutManager); 143 | 144 | loadingLayout.setLoadLayoutListener(() -> { 145 | if (!TextUtils.isEmpty(pdfUrl)) { 146 | loadPdf(pdfUrl); 147 | } 148 | }); 149 | 150 | pageList = new ArrayList<>(); 151 | pageAdapter = new PdfPageAdapter(getContext(), pageList); 152 | contentRv.setAdapter(pageAdapter); 153 | 154 | getOperateView().addOperateListener(this); 155 | 156 | scrollSlider.setScrollSlideListener(scrollY -> { 157 | if (pageCount == 0) return true; 158 | int pageItemHeight = contentRv.getHeight() / pageCount; 159 | int scrollIndex = scrollY / pageItemHeight; 160 | if(scrollIndex >= 0 && scrollIndex < pageLayoutManager.getItemCount()) { 161 | scrollSlider.setTranslationY(scrollY - scrollY % pageItemHeight); 162 | currentIndex = scrollIndex; 163 | pageLayoutManager.scrollToPosition(currentIndex); 164 | getOperateView().setPageIndexText(generatePageIndexText()); 165 | } 166 | return true; 167 | }); 168 | } 169 | 170 | public void loadPdf(String url) { 171 | contentRv.setVisibility(GONE); 172 | loadingLayout.showLoading(); 173 | if (!TextUtils.isEmpty(url)) { 174 | if (url.startsWith("http")) { 175 | pdfUrl = url; 176 | serviceIntent = new Intent(getContext(), DownloadService.class); 177 | serviceIntent.putExtra(DOWNLOAD_URL_KEY, url); 178 | getContext().startService(serviceIntent); 179 | } else { 180 | pdfLocalPath = url; 181 | openPdf(); 182 | } 183 | } 184 | } 185 | 186 | public void setPDFController(AbsControllerBar controller) { 187 | if (controllerContainer == null || controller == null) { 188 | return; 189 | } 190 | this.controllerContainer.removeAllViews(); 191 | this.controllerContainer.addView(controller, 0); 192 | controller.getLayoutParams().width = MATCH_PARENT; 193 | controller.getLayoutParams().height = WRAP_CONTENT; 194 | controller.addOperateListener(this); 195 | } 196 | 197 | private void scrollToPosition() { 198 | pageLayoutManager.scrollToPosition(currentIndex); 199 | getOperateView().setPageIndexText(generatePageIndexText()); 200 | scrollSlider(); 201 | } 202 | 203 | private void scrollSlider() { 204 | int pageItemHeight = contentRv.getHeight() / pageCount; 205 | float scrollDistance = currentIndex * pageItemHeight; 206 | scrollSlider.setTranslationY(scrollDistance); 207 | } 208 | 209 | private AbsControllerBar getOperateView() { 210 | return (AbsControllerBar) controllerContainer.getChildAt(0); 211 | } 212 | 213 | private DownloadResultBroadcast downloadReceiver; 214 | 215 | private void registerResultBroadcast() { 216 | downloadReceiver = new DownloadResultBroadcast(); 217 | downloadReceiver.setResultCallback(this); 218 | IntentFilter intentFilter = new IntentFilter(); 219 | intentFilter.addAction(DOWNLOAD_ACTION); 220 | getContext().registerReceiver(downloadReceiver, intentFilter); 221 | } 222 | 223 | private void unregisterResultBroadcast() { 224 | getContext().unregisterReceiver(downloadReceiver); 225 | } 226 | 227 | private String generatePageIndexText() { 228 | return (currentIndex + 1) + "/" + pageCount; 229 | } 230 | 231 | private void openPdf() { 232 | renderTask = new RenderTask(); 233 | renderTask.execute(); 234 | } 235 | 236 | private ParcelFileDescriptor getFileDescriptor() { 237 | try { 238 | File file; 239 | if (pdfLocalPath.contains("asset")) { 240 | file = FileUtils.writeAssetsToFile(getContext(), pdfLocalPath); 241 | } else { 242 | file = new File(pdfLocalPath); 243 | } 244 | parcelFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); 245 | } catch (Exception e) { 246 | e.printStackTrace(); 247 | } 248 | return parcelFileDescriptor; 249 | } 250 | 251 | @Override 252 | public void clickPrevious() { 253 | currentIndex = pageLayoutManager.getCurrentPosition(); 254 | if (currentIndex - 1 >= 0) { 255 | currentIndex--; 256 | scrollToPosition(); 257 | } 258 | } 259 | 260 | @Override 261 | public void clickNext() { 262 | currentIndex = pageLayoutManager.getCurrentPosition(); 263 | if(currentIndex + 1 < pageLayoutManager.getItemCount()) { 264 | currentIndex++; 265 | scrollToPosition(); 266 | } 267 | } 268 | 269 | public void setPreviousText(String previousText) { 270 | if (controllerContainer != null && previousText != null) { 271 | AbsControllerBar controllerBar = (AbsControllerBar) controllerContainer.getChildAt(0); 272 | if (controllerBar != null) { 273 | controllerBar.setPreviousText(previousText); 274 | } 275 | } 276 | } 277 | 278 | public void setNextText(String nextText) { 279 | if (controllerContainer != null && nextText != null) { 280 | AbsControllerBar controllerBar = (AbsControllerBar) controllerContainer.getChildAt(0); 281 | if (controllerBar != null) { 282 | controllerBar.setNextText(nextText); 283 | } 284 | } 285 | } 286 | 287 | @Override 288 | public void downloadSuccess(String path) { 289 | 290 | } 291 | 292 | @Override 293 | public void downloadFail() { 294 | loadingLayout.showFail(); 295 | } 296 | 297 | @Override 298 | public void downloadComplete(String path) { 299 | PdfLog.logDebug("path: " + path); 300 | pdfLocalPath = path; 301 | if (TextUtils.isEmpty(pdfLocalPath)) { 302 | return; 303 | } 304 | openPdf(); 305 | } 306 | 307 | public class RenderTask extends AsyncTask { 308 | 309 | @Override 310 | protected Boolean doInBackground(Void... voids) { 311 | try { 312 | currentIndex = 0; 313 | pdfRenderer = new PdfRenderer(getFileDescriptor()); 314 | pageCount = pdfRenderer.getPageCount(); 315 | pageList.clear(); 316 | for (int i=0; i { 28 | 29 | final private Context context; 30 | final private List pageList; 31 | 32 | public PdfPageAdapter(Context context, List pageList) { 33 | this.context = context; 34 | this.pageList = pageList; 35 | } 36 | 37 | @NonNull 38 | @Override 39 | public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { 40 | return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.layout_page_item, null)); 41 | } 42 | 43 | 44 | @Override 45 | public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) { 46 | Bitmap item = pageList.get(i); 47 | viewHolder.itemIv.setLayoutParams(new FrameLayout.LayoutParams(context.getResources().getDisplayMetrics().widthPixels, context.getResources().getDisplayMetrics().heightPixels - 300)); 48 | viewHolder.itemIv.setImageBitmap(item); 49 | } 50 | 51 | @Override 52 | public int getItemCount() { 53 | return pageList.size(); 54 | } 55 | 56 | @Override 57 | public void onViewAttachedToWindow(@NonNull ViewHolder holder) { 58 | super.onViewAttachedToWindow(holder); 59 | holder.itemIv.setScaleType(ImageView.ScaleType.FIT_CENTER); 60 | } 61 | 62 | static class ViewHolder extends RecyclerView.ViewHolder { 63 | 64 | ScaleImageView itemIv; 65 | 66 | public ViewHolder(@NonNull View itemView) { 67 | super(itemView); 68 | itemIv = itemView.findViewById(R.id.pdf_page_iv); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/constants/Constants.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview.constants; 2 | 3 | /** 4 | * Date: 2021/1/26 5 | * Author: Yang 6 | * Describe: 7 | */ 8 | public class Constants { 9 | 10 | public static final String DOWNLOAD_ACTION = "DOWN_LOAD_ACTION"; 11 | public static final String DOWNLOAD_STATE = "DOWNLOAD_STATE"; 12 | public static final String DOWNLOAD_RESULT = "DOWNLOAD_RESULT"; 13 | 14 | public static class DownloadState { 15 | public static final int SUCCESS = 1; 16 | public static final int FAIL = 2; 17 | public static final int COMPLETE = 3; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/download/DownloadManager.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview.download; 2 | 3 | import android.content.Context; 4 | 5 | import androidx.annotation.NonNull; 6 | 7 | import com.zjy.pdfview.utils.FileUtils; 8 | import com.zjy.pdfview.utils.PdfLog; 9 | 10 | import java.io.File; 11 | import java.io.IOException; 12 | 13 | import okhttp3.Call; 14 | import okhttp3.Callback; 15 | import okhttp3.OkHttpClient; 16 | import okhttp3.Request; 17 | import okhttp3.Response; 18 | 19 | /** 20 | * Date: 2021/1/26 21 | * Author: Yang 22 | * Describe: 23 | */ 24 | public class DownloadManager { 25 | 26 | private IDownloadCallback mCallback; 27 | 28 | public DownloadManager(IDownloadCallback callback) { 29 | mCallback = callback; 30 | } 31 | 32 | public void downloadFile(final Context context, final String url) { 33 | final long startTime = System.currentTimeMillis(); 34 | PdfLog.logInfo("download url=" + url); 35 | PdfLog.logInfo("download startTime=" + startTime); 36 | 37 | Request request = new Request.Builder().url(url).build(); 38 | new OkHttpClient().newCall(request).enqueue(new Callback() { 39 | @Override 40 | public void onFailure(@NonNull Call call, @NonNull IOException e) { 41 | // 下载失败 42 | //e.printStackTrace(); 43 | PdfLog.logError("download failed" + e.toString()); 44 | if (mCallback != null) { 45 | mCallback.downloadFail(); 46 | } 47 | } 48 | 49 | @Override 50 | public void onResponse(@NonNull Call call, @NonNull Response response) { 51 | String resultPath = ""; 52 | try { 53 | File dest = FileUtils.writeNetToFile(context, url, response); 54 | PdfLog.logInfo("download totalTime=" + (System.currentTimeMillis() - startTime)); 55 | resultPath = dest.getAbsolutePath(); 56 | if (mCallback != null) { 57 | mCallback.downloadSuccess(resultPath); 58 | } 59 | } catch (Exception e) { 60 | e.printStackTrace(); 61 | PdfLog.logError("download failed: " + e.getMessage()); 62 | if (mCallback != null) { 63 | mCallback.downloadFail(); 64 | } 65 | } finally { 66 | if (mCallback != null) { 67 | mCallback.downloadComplete(resultPath); 68 | } 69 | } 70 | } 71 | }); 72 | } 73 | 74 | public void cancel() { 75 | //mContext = null; 76 | 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/download/DownloadResultBroadcast.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview.download; 2 | 3 | import android.content.BroadcastReceiver; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | 7 | import static com.zjy.pdfview.constants.Constants.DOWNLOAD_RESULT; 8 | import static com.zjy.pdfview.constants.Constants.DOWNLOAD_STATE; 9 | import static com.zjy.pdfview.constants.Constants.DownloadState.COMPLETE; 10 | import static com.zjy.pdfview.constants.Constants.DownloadState.FAIL; 11 | import static com.zjy.pdfview.constants.Constants.DownloadState.SUCCESS; 12 | 13 | /** 14 | * Date: 2021/1/26 15 | * Author: Yang 16 | * Describe: 17 | */ 18 | public class DownloadResultBroadcast extends BroadcastReceiver { 19 | 20 | IDownloadCallback mCallback; 21 | 22 | public void setResultCallback(IDownloadCallback callback) { 23 | mCallback = callback; 24 | } 25 | 26 | @Override 27 | public void onReceive(Context context, Intent intent) { 28 | int state = intent.getIntExtra(DOWNLOAD_STATE, COMPLETE); 29 | String resultPath = intent.getStringExtra(DOWNLOAD_RESULT); 30 | if (mCallback != null) { 31 | switch (state) { 32 | case SUCCESS: 33 | mCallback.downloadSuccess(resultPath); 34 | break; 35 | case FAIL: 36 | mCallback.downloadFail(); 37 | break; 38 | case COMPLETE: 39 | mCallback.downloadComplete(resultPath); 40 | break; 41 | } 42 | } 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/download/DownloadService.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview.download; 2 | 3 | import android.app.IntentService; 4 | import android.content.Intent; 5 | import android.text.TextUtils; 6 | 7 | import androidx.annotation.Nullable; 8 | 9 | import com.zjy.pdfview.constants.Constants; 10 | import com.zjy.pdfview.utils.PdfLog; 11 | 12 | import static com.zjy.pdfview.constants.Constants.DOWNLOAD_ACTION; 13 | import static com.zjy.pdfview.constants.Constants.DOWNLOAD_RESULT; 14 | import static com.zjy.pdfview.constants.Constants.DOWNLOAD_STATE; 15 | 16 | /** 17 | * Date: 2021/1/26 18 | * Author: Yang 19 | * Describe: 20 | */ 21 | public class DownloadService extends IntentService { 22 | 23 | //下载地址 24 | public static final String DOWNLOAD_URL_KEY = "DOWNLOAD_URL_KEY"; 25 | 26 | private String downLoadUrl; 27 | private DownloadManager downloadManager; 28 | 29 | 30 | public DownloadService() { 31 | super("download_pdf"); 32 | } 33 | 34 | @Override 35 | protected void onHandleIntent(@Nullable Intent intent) { 36 | PdfLog.logDebug("onHandleIntent"); 37 | if (intent != null) { 38 | downLoadUrl = intent.getStringExtra(DOWNLOAD_URL_KEY); 39 | } 40 | if (!TextUtils.isEmpty(downLoadUrl)){ 41 | downloadManager = new DownloadManager(new IDownloadCallback() { 42 | @Override 43 | public void downloadSuccess(String resultPath) { 44 | sendDownloadState(Constants.DownloadState.SUCCESS, resultPath); 45 | } 46 | 47 | @Override 48 | public void downloadFail() { 49 | sendDownloadState(Constants.DownloadState.FAIL, ""); 50 | } 51 | 52 | @Override 53 | public void downloadComplete(String path) { 54 | sendDownloadState(Constants.DownloadState.COMPLETE, path); 55 | } 56 | }); 57 | downloadManager.downloadFile(getApplicationContext(), downLoadUrl); 58 | } 59 | } 60 | 61 | private void sendDownloadState(int state, String path) { 62 | Intent it = new Intent(); 63 | it.setAction(DOWNLOAD_ACTION); 64 | if (!TextUtils.isEmpty(path)) { 65 | it.putExtra(DOWNLOAD_RESULT, path); 66 | } 67 | it.putExtra(DOWNLOAD_STATE, state); 68 | sendBroadcast(it); 69 | } 70 | 71 | @Override 72 | public void onDestroy() { 73 | super.onDestroy(); 74 | if (downloadManager != null){ 75 | downloadManager.cancel(); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/download/IDownloadCallback.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview.download; 2 | 3 | /** 4 | * Date: 2021/1/26 5 | * Author: Yang 6 | * Describe: 7 | */ 8 | public interface IDownloadCallback { 9 | 10 | void downloadSuccess(String path); 11 | 12 | void downloadFail(); 13 | 14 | void downloadComplete(String path); 15 | 16 | } 17 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/utils/FileUtils.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview.utils; 2 | 3 | import android.content.Context; 4 | 5 | import java.io.File; 6 | import java.io.FileOutputStream; 7 | import java.io.IOException; 8 | import java.io.InputStream; 9 | 10 | import okhttp3.Response; 11 | import okio.BufferedSink; 12 | import okio.Okio; 13 | import okio.Sink; 14 | 15 | public class FileUtils { 16 | 17 | public static File writeAssetsToFile(Context context, String assetPath) throws IOException { 18 | String fileName = assetPath.substring(assetPath.lastIndexOf("/") + 1); 19 | File resultFile = checkCacheSize(context, assetPath); 20 | if (!resultFile.exists()) { 21 | boolean createResult = resultFile.createNewFile(); 22 | if (!createResult) { 23 | return null; 24 | } 25 | } 26 | InputStream is = context.getAssets().open(fileName); 27 | FileOutputStream fos = null; 28 | try { 29 | byte[] data = new byte[2048]; 30 | int readBuffer; 31 | fos = new FileOutputStream(resultFile); 32 | while ((readBuffer = is.read(data)) > -1) { 33 | fos.write(data, 0, readBuffer); 34 | } 35 | } catch (Exception ex) { 36 | PdfLog.logError("Exception: " + ex); 37 | } finally { 38 | if (fos != null) { 39 | fos.close(); 40 | } 41 | } 42 | return resultFile; 43 | } 44 | 45 | public static File writeNetToFile(Context context, String url, Response response) throws IOException{ 46 | Sink sink; 47 | BufferedSink bufferedSink = null; 48 | File dest = null; 49 | try { 50 | dest = checkCacheSize(context, url); 51 | if (dest.exists()) { 52 | PdfLog.logError("download cache exist"); 53 | return dest; 54 | } 55 | sink = Okio.sink(dest); 56 | bufferedSink = Okio.buffer(sink); 57 | bufferedSink.writeAll(response.body().source()); 58 | 59 | bufferedSink.close(); 60 | PdfLog.logInfo("download success"); 61 | 62 | } catch (Exception e) { 63 | e.printStackTrace(); 64 | PdfLog.logError("download failed: " + e.getMessage()); 65 | } finally { 66 | if (bufferedSink != null) { 67 | bufferedSink.close(); 68 | } 69 | } 70 | return dest; 71 | } 72 | 73 | private static File checkCacheSize(Context context, String url) { 74 | String folderPath = context.getFilesDir().getAbsolutePath() + "/pdf/"; 75 | File folder = new File(folderPath); 76 | if (!folder.exists()) { 77 | folder.mkdir(); 78 | } 79 | File[] cacheList = folder.listFiles(); 80 | if (cacheList != null && cacheList.length >= 10) { 81 | for (File childFile : cacheList) { 82 | childFile.delete(); 83 | } 84 | } 85 | return new File(folderPath, url.substring(url.lastIndexOf("/") + 1)); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/utils/PdfLog.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview.utils; 2 | 3 | import android.util.Log; 4 | 5 | import com.zjy.pdfview.BuildConfig; 6 | 7 | /** 8 | * Date: 2021/1/26 9 | * Author: Yang 10 | * Describe: 组件日志 11 | */ 12 | public class PdfLog { 13 | 14 | private static final String LOG_TAG = "PdfLog"; 15 | 16 | private static boolean isDebug() { 17 | return BuildConfig.DEBUG; 18 | } 19 | 20 | public static void logInfo(String message) { 21 | if (!isDebug()) 22 | return; 23 | if (message == null) { 24 | Log.i(LOG_TAG, "null"); 25 | return; 26 | } 27 | Log.i(LOG_TAG, message); 28 | } 29 | 30 | public static void logDebug(String message) { 31 | if (!isDebug()) 32 | return; 33 | if (message == null) { 34 | Log.d(LOG_TAG, "null"); 35 | return; 36 | } 37 | Log.d(LOG_TAG, message); 38 | } 39 | 40 | public static void logWarn(String message) { 41 | if (!isDebug()) 42 | return; 43 | if (message == null) { 44 | Log.w(LOG_TAG, "null"); 45 | return; 46 | } 47 | Log.w(LOG_TAG, message); 48 | } 49 | 50 | public static void logError(String message) { 51 | if (!isDebug()) 52 | return; 53 | if (message == null) { 54 | Log.e(LOG_TAG, "null"); 55 | return; 56 | } 57 | Log.e(LOG_TAG, message); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/utils/ReflectUtils.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview.utils; 2 | 3 | import java.lang.reflect.AccessibleObject; 4 | import java.lang.reflect.Constructor; 5 | import java.lang.reflect.Field; 6 | import java.lang.reflect.InvocationHandler; 7 | import java.lang.reflect.Member; 8 | import java.lang.reflect.Method; 9 | import java.lang.reflect.Modifier; 10 | import java.lang.reflect.Proxy; 11 | import java.util.ArrayList; 12 | import java.util.Arrays; 13 | import java.util.Collections; 14 | import java.util.Comparator; 15 | import java.util.List; 16 | import java.util.Map; 17 | 18 | 19 | 20 | /** 21 | *
 22 |  *     author: Blankj
 23 |  *     blog  : http://blankj.com
 24 |  *     time  : 2017/12/15
 25 |  *     desc  : utils about reflect
 26 |  * 
27 | */ 28 | public final class ReflectUtils { 29 | 30 | private final Class type; 31 | 32 | private final Object object; 33 | 34 | private ReflectUtils(final Class type) { 35 | this(type, type); 36 | } 37 | 38 | private ReflectUtils(final Class type, Object object) { 39 | this.type = type; 40 | this.object = object; 41 | } 42 | 43 | /////////////////////////////////////////////////////////////////////////// 44 | // reflect 45 | /////////////////////////////////////////////////////////////////////////// 46 | 47 | /** 48 | * Reflect the class. 49 | * 50 | * @param className The name of class. 51 | * @return the single {@link ReflectUtils} instance 52 | * @throws ReflectException if reflect unsuccessfully 53 | */ 54 | public static ReflectUtils reflect(final String className) 55 | throws ReflectException { 56 | return reflect(forName(className)); 57 | } 58 | 59 | /** 60 | * Reflect the class. 61 | * 62 | * @param className The name of class. 63 | * @param classLoader The loader of class. 64 | * @return the single {@link ReflectUtils} instance 65 | * @throws ReflectException if reflect unsuccessfully 66 | */ 67 | public static ReflectUtils reflect(final String className, final ClassLoader classLoader) 68 | throws ReflectException { 69 | return reflect(forName(className, classLoader)); 70 | } 71 | 72 | /** 73 | * Reflect the class. 74 | * 75 | * @param clazz The class. 76 | * @return the single {@link ReflectUtils} instance 77 | * @throws ReflectException if reflect unsuccessfully 78 | */ 79 | public static ReflectUtils reflect(final Class clazz) 80 | throws ReflectException { 81 | return new ReflectUtils(clazz); 82 | } 83 | 84 | /** 85 | * Reflect the class. 86 | * 87 | * @param object The object. 88 | * @return the single {@link ReflectUtils} instance 89 | * @throws ReflectException if reflect unsuccessfully 90 | */ 91 | public static ReflectUtils reflect(final Object object) 92 | throws ReflectException { 93 | return new ReflectUtils(object == null ? Object.class : object.getClass(), object); 94 | } 95 | 96 | private static Class forName(String className) { 97 | try { 98 | return Class.forName(className); 99 | } catch (ClassNotFoundException e) { 100 | throw new ReflectException(e); 101 | } 102 | } 103 | 104 | private static Class forName(String name, ClassLoader classLoader) { 105 | try { 106 | return Class.forName(name, true, classLoader); 107 | } catch (ClassNotFoundException e) { 108 | throw new ReflectException(e); 109 | } 110 | } 111 | 112 | /////////////////////////////////////////////////////////////////////////// 113 | // newInstance 114 | /////////////////////////////////////////////////////////////////////////// 115 | 116 | /** 117 | * Create and initialize a new instance. 118 | * 119 | * @return the single {@link ReflectUtils} instance 120 | */ 121 | public ReflectUtils newInstance() { 122 | return newInstance(new Object[0]); 123 | } 124 | 125 | /** 126 | * Create and initialize a new instance. 127 | * 128 | * @param args The args. 129 | * @return the single {@link ReflectUtils} instance 130 | */ 131 | public ReflectUtils newInstance(Object... args) { 132 | Class[] types = getArgsType(args); 133 | try { 134 | Constructor constructor = type().getDeclaredConstructor(types); 135 | return newInstance(constructor, args); 136 | } catch (NoSuchMethodException e) { 137 | List> list = new ArrayList<>(); 138 | for (Constructor constructor : type().getDeclaredConstructors()) { 139 | if (match(constructor.getParameterTypes(), types)) { 140 | list.add(constructor); 141 | } 142 | } 143 | if (list.isEmpty()) { 144 | throw new ReflectException(e); 145 | } else { 146 | sortConstructors(list); 147 | return newInstance(list.get(0), args); 148 | } 149 | } 150 | } 151 | 152 | private Class[] getArgsType(final Object... args) { 153 | if (args == null) return new Class[0]; 154 | Class[] result = new Class[args.length]; 155 | for (int i = 0; i < args.length; i++) { 156 | Object value = args[i]; 157 | result[i] = value == null ? NULL.class : value.getClass(); 158 | } 159 | return result; 160 | } 161 | 162 | private void sortConstructors(List> list) { 163 | Collections.sort(list, new Comparator>() { 164 | @Override 165 | public int compare(Constructor o1, Constructor o2) { 166 | Class[] types1 = o1.getParameterTypes(); 167 | Class[] types2 = o2.getParameterTypes(); 168 | int len = types1.length; 169 | for (int i = 0; i < len; i++) { 170 | if (!types1[i].equals(types2[i])) { 171 | if (wrapper(types1[i]).isAssignableFrom(wrapper(types2[i]))) { 172 | return 1; 173 | } else { 174 | return -1; 175 | } 176 | } 177 | } 178 | return 0; 179 | } 180 | }); 181 | } 182 | 183 | private ReflectUtils newInstance(final Constructor constructor, final Object... args) { 184 | try { 185 | return new ReflectUtils( 186 | constructor.getDeclaringClass(), 187 | accessible(constructor).newInstance(args) 188 | ); 189 | } catch (Exception e) { 190 | throw new ReflectException(e); 191 | } 192 | } 193 | 194 | /////////////////////////////////////////////////////////////////////////// 195 | // field 196 | /////////////////////////////////////////////////////////////////////////// 197 | 198 | /** 199 | * Get the field. 200 | * 201 | * @param name The name of field. 202 | * @return the single {@link ReflectUtils} instance 203 | */ 204 | public ReflectUtils field(final String name) { 205 | try { 206 | Field field = getField(name); 207 | return new ReflectUtils(field.getType(), field.get(object)); 208 | } catch (IllegalAccessException e) { 209 | throw new ReflectException(e); 210 | } 211 | } 212 | 213 | /** 214 | * Set the field. 215 | * 216 | * @param name The name of field. 217 | * @param value The value. 218 | * @return the single {@link ReflectUtils} instance 219 | */ 220 | public ReflectUtils field(String name, Object value) { 221 | try { 222 | Field field = getField(name); 223 | field.set(object, unwrap(value)); 224 | return this; 225 | } catch (Exception e) { 226 | throw new ReflectException(e); 227 | } 228 | } 229 | 230 | private Field getField(String name) throws IllegalAccessException { 231 | Field field = getAccessibleField(name); 232 | if ((field.getModifiers() & Modifier.FINAL) == Modifier.FINAL) { 233 | try { 234 | Field modifiersField = Field.class.getDeclaredField("modifiers"); 235 | modifiersField.setAccessible(true); 236 | modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); 237 | } catch (NoSuchFieldException ignore) { 238 | // runs in android will happen 239 | field.setAccessible(true); 240 | } 241 | } 242 | return field; 243 | } 244 | 245 | private Field getAccessibleField(String name) { 246 | Class type = type(); 247 | try { 248 | return accessible(type.getField(name)); 249 | } catch (NoSuchFieldException e) { 250 | do { 251 | try { 252 | return accessible(type.getDeclaredField(name)); 253 | } catch (NoSuchFieldException ignore) { 254 | } 255 | type = type.getSuperclass(); 256 | } while (type != null); 257 | throw new ReflectException(e); 258 | } 259 | } 260 | 261 | private Object unwrap(Object object) { 262 | if (object instanceof ReflectUtils) { 263 | return ((ReflectUtils) object).get(); 264 | } 265 | return object; 266 | } 267 | 268 | /////////////////////////////////////////////////////////////////////////// 269 | // method 270 | /////////////////////////////////////////////////////////////////////////// 271 | 272 | /** 273 | * Invoke the method. 274 | * 275 | * @param name The name of method. 276 | * @return the single {@link ReflectUtils} instance 277 | * @throws ReflectException if reflect unsuccessfully 278 | */ 279 | public ReflectUtils method(final String name) throws ReflectException { 280 | return method(name, new Object[0]); 281 | } 282 | 283 | /** 284 | * Invoke the method. 285 | * 286 | * @param name The name of method. 287 | * @param args The args. 288 | * @return the single {@link ReflectUtils} instance 289 | * @throws ReflectException if reflect unsuccessfully 290 | */ 291 | public ReflectUtils method(final String name, final Object... args) throws ReflectException { 292 | Class[] types = getArgsType(args); 293 | try { 294 | Method method = exactMethod(name, types); 295 | return method(method, object, args); 296 | } catch (NoSuchMethodException e) { 297 | try { 298 | Method method = similarMethod(name, types); 299 | return method(method, object, args); 300 | } catch (NoSuchMethodException e1) { 301 | throw new ReflectException(e1); 302 | } 303 | } 304 | } 305 | 306 | private ReflectUtils method(final Method method, final Object obj, final Object... args) { 307 | try { 308 | accessible(method); 309 | if (method.getReturnType() == void.class) { 310 | method.invoke(obj, args); 311 | return reflect(obj); 312 | } else { 313 | return reflect(method.invoke(obj, args)); 314 | } 315 | } catch (Exception e) { 316 | throw new ReflectException(e); 317 | } 318 | } 319 | 320 | private Method exactMethod(final String name, final Class[] types) 321 | throws NoSuchMethodException { 322 | Class type = type(); 323 | try { 324 | return type.getMethod(name, types); 325 | } catch (NoSuchMethodException e) { 326 | do { 327 | try { 328 | return type.getDeclaredMethod(name, types); 329 | } catch (NoSuchMethodException ignore) { 330 | } 331 | type = type.getSuperclass(); 332 | } while (type != null); 333 | throw new NoSuchMethodException(); 334 | } 335 | } 336 | 337 | private Method similarMethod(final String name, final Class[] types) 338 | throws NoSuchMethodException { 339 | Class type = type(); 340 | List methods = new ArrayList<>(); 341 | for (Method method : type.getMethods()) { 342 | if (isSimilarSignature(method, name, types)) { 343 | methods.add(method); 344 | } 345 | } 346 | if (!methods.isEmpty()) { 347 | sortMethods(methods); 348 | return methods.get(0); 349 | } 350 | do { 351 | for (Method method : type.getDeclaredMethods()) { 352 | if (isSimilarSignature(method, name, types)) { 353 | methods.add(method); 354 | } 355 | } 356 | if (!methods.isEmpty()) { 357 | sortMethods(methods); 358 | return methods.get(0); 359 | } 360 | type = type.getSuperclass(); 361 | } while (type != null); 362 | 363 | throw new NoSuchMethodException("No similar method " + name + " with params " 364 | + Arrays.toString(types) + " could be found on type " + type() + "."); 365 | } 366 | 367 | private void sortMethods(final List methods) { 368 | Collections.sort(methods, new Comparator() { 369 | @Override 370 | public int compare(Method o1, Method o2) { 371 | Class[] types1 = o1.getParameterTypes(); 372 | Class[] types2 = o2.getParameterTypes(); 373 | int len = types1.length; 374 | for (int i = 0; i < len; i++) { 375 | if (!types1[i].equals(types2[i])) { 376 | if (wrapper(types1[i]).isAssignableFrom(wrapper(types2[i]))) { 377 | return 1; 378 | } else { 379 | return -1; 380 | } 381 | } 382 | } 383 | return 0; 384 | } 385 | }); 386 | } 387 | 388 | private boolean isSimilarSignature(final Method possiblyMatchingMethod, 389 | final String desiredMethodName, 390 | final Class[] desiredParamTypes) { 391 | return possiblyMatchingMethod.getName().equals(desiredMethodName) 392 | && match(possiblyMatchingMethod.getParameterTypes(), desiredParamTypes); 393 | } 394 | 395 | private boolean match(final Class[] declaredTypes, final Class[] actualTypes) { 396 | if (declaredTypes.length == actualTypes.length) { 397 | for (int i = 0; i < actualTypes.length; i++) { 398 | if (actualTypes[i] == NULL.class 399 | || wrapper(declaredTypes[i]).isAssignableFrom(wrapper(actualTypes[i]))) { 400 | continue; 401 | } 402 | return false; 403 | } 404 | return true; 405 | } else { 406 | return false; 407 | } 408 | } 409 | 410 | private T accessible(T accessible) { 411 | if (accessible == null) return null; 412 | if (accessible instanceof Member) { 413 | Member member = (Member) accessible; 414 | if (Modifier.isPublic(member.getModifiers()) 415 | && Modifier.isPublic(member.getDeclaringClass().getModifiers())) { 416 | return accessible; 417 | } 418 | } 419 | if (!accessible.isAccessible()) accessible.setAccessible(true); 420 | return accessible; 421 | } 422 | 423 | /////////////////////////////////////////////////////////////////////////// 424 | // proxy 425 | /////////////////////////////////////////////////////////////////////////// 426 | 427 | /** 428 | * Create a proxy for the wrapped object allowing to typesafely invoke 429 | * methods on it using a custom interface. 430 | * 431 | * @param proxyType The interface type that is implemented by the proxy. 432 | * @return a proxy for the wrapped object 433 | */ 434 | @SuppressWarnings("unchecked") 435 | public

P proxy(final Class

proxyType) { 436 | final boolean isMap = (object instanceof Map); 437 | final InvocationHandler handler = new InvocationHandler() { 438 | @Override 439 | @SuppressWarnings("null") 440 | public Object invoke(Object proxy, Method method, Object[] args) { 441 | String name = method.getName(); 442 | try { 443 | return reflect(object).method(name, args).get(); 444 | } catch (ReflectException e) { 445 | if (isMap) { 446 | Map map = (Map) object; 447 | int length = (args == null ? 0 : args.length); 448 | 449 | if (length == 0 && name.startsWith("get")) { 450 | return map.get(property(name.substring(3))); 451 | } else if (length == 0 && name.startsWith("is")) { 452 | return map.get(property(name.substring(2))); 453 | } else if (length == 1 && name.startsWith("set")) { 454 | map.put(property(name.substring(3)), args[0]); 455 | return null; 456 | } 457 | } 458 | throw e; 459 | } 460 | } 461 | }; 462 | return (P) Proxy.newProxyInstance(proxyType.getClassLoader(), 463 | new Class[]{proxyType}, 464 | handler); 465 | } 466 | 467 | /** 468 | * Get the POJO property name of an getter/setter 469 | */ 470 | private static String property(String string) { 471 | int length = string.length(); 472 | 473 | if (length == 0) { 474 | return ""; 475 | } else if (length == 1) { 476 | return string.toLowerCase(); 477 | } else { 478 | return string.substring(0, 1).toLowerCase() + string.substring(1); 479 | } 480 | } 481 | 482 | private Class type() { 483 | return type; 484 | } 485 | 486 | private Class wrapper(final Class type) { 487 | if (type == null) { 488 | return null; 489 | } else if (type.isPrimitive()) { 490 | if (boolean.class == type) { 491 | return Boolean.class; 492 | } else if (int.class == type) { 493 | return Integer.class; 494 | } else if (long.class == type) { 495 | return Long.class; 496 | } else if (short.class == type) { 497 | return Short.class; 498 | } else if (byte.class == type) { 499 | return Byte.class; 500 | } else if (double.class == type) { 501 | return Double.class; 502 | } else if (float.class == type) { 503 | return Float.class; 504 | } else if (char.class == type) { 505 | return Character.class; 506 | } else if (void.class == type) { 507 | return Void.class; 508 | } 509 | } 510 | return type; 511 | } 512 | 513 | /** 514 | * Get the result. 515 | * 516 | * @param The value type. 517 | * @return the result 518 | */ 519 | @SuppressWarnings("unchecked") 520 | public T get() { 521 | return (T) object; 522 | } 523 | 524 | @Override 525 | public int hashCode() { 526 | return object.hashCode(); 527 | } 528 | 529 | @Override 530 | public boolean equals(Object obj) { 531 | return obj instanceof ReflectUtils && object.equals(((ReflectUtils) obj).get()); 532 | } 533 | 534 | @Override 535 | public String toString() { 536 | return object.toString(); 537 | } 538 | 539 | private static class NULL { 540 | } 541 | 542 | public static class ReflectException extends RuntimeException { 543 | 544 | private static final long serialVersionUID = 858774075258496016L; 545 | 546 | public ReflectException(String message) { 547 | super(message); 548 | } 549 | 550 | public ReflectException(String message, Throwable cause) { 551 | super(message, cause); 552 | } 553 | 554 | public ReflectException(Throwable cause) { 555 | super(cause); 556 | } 557 | } 558 | } 559 | 560 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/utils/layoutmanager/MyPagerSnapHelper.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview.utils.layoutmanager; 2 | 3 | import android.graphics.PointF; 4 | import android.util.DisplayMetrics; 5 | import android.view.View; 6 | 7 | import androidx.annotation.NonNull; 8 | import androidx.annotation.Nullable; 9 | import androidx.recyclerview.widget.LinearSmoothScroller; 10 | import androidx.recyclerview.widget.OrientationHelper; 11 | import androidx.recyclerview.widget.RecyclerView; 12 | import androidx.recyclerview.widget.SnapHelper; 13 | 14 | import com.zjy.pdfview.utils.ReflectUtils; 15 | 16 | 17 | public class MyPagerSnapHelper extends SnapHelper { 18 | 19 | private static final String TAG = MyPagerSnapHelper.class.getSimpleName(); 20 | 21 | private static final int MAX_SCROLL_ON_FLING_DURATION = 150; 22 | @Nullable 23 | private OrientationHelper mVerticalHelper; 24 | @Nullable 25 | private OrientationHelper mHorizontalHelper; 26 | 27 | @Nullable 28 | public int[] calculateDistanceToFinalSnap(@NonNull RecyclerView.LayoutManager layoutManager, @NonNull View targetView) { 29 | int[] out = new int[2]; 30 | if (layoutManager.canScrollHorizontally()) { 31 | out[0] = this.distanceToCenter(layoutManager, targetView, this.getHorizontalHelper(layoutManager)); 32 | } else { 33 | out[0] = 0; 34 | } 35 | 36 | if (layoutManager.canScrollVertically()) { 37 | out[1] = this.distanceToCenter(layoutManager, targetView, this.getVerticalHelper(layoutManager)); 38 | } else { 39 | out[1] = 0; 40 | } 41 | 42 | return out; 43 | } 44 | 45 | @Nullable 46 | public View findSnapView(RecyclerView.LayoutManager layoutManager) { 47 | if (layoutManager.canScrollVertically()) { 48 | return this.findCenterView(layoutManager, this.getVerticalHelper(layoutManager)); 49 | } else { 50 | return layoutManager.canScrollHorizontally() ? this.findCenterView(layoutManager, this.getHorizontalHelper(layoutManager)) : null; 51 | } 52 | } 53 | 54 | public int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX, int velocityY) { 55 | int itemCount = layoutManager.getItemCount(); 56 | if (itemCount == 0) { 57 | return -1; 58 | } else { 59 | View mStartMostChildView = null; 60 | if (layoutManager.canScrollVertically()) { 61 | mStartMostChildView = this.findStartView(layoutManager, this.getVerticalHelper(layoutManager)); 62 | } else if (layoutManager.canScrollHorizontally()) { 63 | mStartMostChildView = this.findStartView(layoutManager, this.getHorizontalHelper(layoutManager)); 64 | } 65 | 66 | if (mStartMostChildView == null) { 67 | return -1; 68 | } else { 69 | int centerPosition = layoutManager.getPosition(mStartMostChildView); 70 | if (centerPosition == -1) { 71 | return -1; 72 | } else { 73 | if (Math.abs(velocityY) < 500) return centerPosition; 74 | 75 | boolean forwardDirection; 76 | if (layoutManager.canScrollHorizontally()) { 77 | forwardDirection = velocityX > 0; 78 | } else { 79 | forwardDirection = velocityY > 0; 80 | } 81 | 82 | boolean reverseLayout = false; 83 | if (layoutManager instanceof RecyclerView.SmoothScroller.ScrollVectorProvider) { 84 | RecyclerView.SmoothScroller.ScrollVectorProvider vectorProvider = (RecyclerView.SmoothScroller.ScrollVectorProvider) layoutManager; 85 | PointF vectorForEnd = vectorProvider.computeScrollVectorForPosition(itemCount - 1); 86 | if (vectorForEnd != null) { 87 | reverseLayout = vectorForEnd.x < 0.0F || vectorForEnd.y < 0.0F; 88 | } 89 | } 90 | 91 | return reverseLayout ? (forwardDirection ? centerPosition - 1 : centerPosition) : (forwardDirection ? centerPosition + 1 : centerPosition); 92 | } 93 | } 94 | } 95 | } 96 | 97 | protected LinearSmoothScroller createSnapScroller(RecyclerView.LayoutManager layoutManager) { 98 | final RecyclerView mRecyclerView = ReflectUtils.reflect(this).field("mRecyclerView").get(); 99 | return !(layoutManager instanceof RecyclerView.SmoothScroller.ScrollVectorProvider) ? null : new LinearSmoothScroller(mRecyclerView.getContext()) { 100 | protected void onTargetFound(View targetView, RecyclerView.State state, Action action) { 101 | int[] snapDistances = calculateDistanceToFinalSnap(mRecyclerView.getLayoutManager(), targetView); 102 | int dx = snapDistances[0]; 103 | int dy = snapDistances[1]; 104 | int time = this.calculateTimeForDeceleration(Math.max(Math.abs(dx), Math.abs(dy))); 105 | if (time > 0) { 106 | action.update(dx, dy, time, this.mDecelerateInterpolator); 107 | } 108 | 109 | } 110 | 111 | protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) { 112 | return 100.0F / (float) displayMetrics.densityDpi; 113 | } 114 | 115 | protected int calculateTimeForScrolling(int dx) { 116 | return Math.min(MAX_SCROLL_ON_FLING_DURATION, super.calculateTimeForScrolling(dx)); 117 | } 118 | }; 119 | } 120 | 121 | private int distanceToCenter(@NonNull RecyclerView.LayoutManager layoutManager, @NonNull View targetView, OrientationHelper helper) { 122 | int childCenter = helper.getDecoratedStart(targetView) + helper.getDecoratedMeasurement(targetView) / 2; 123 | int containerCenter; 124 | if (layoutManager.getClipToPadding()) { 125 | containerCenter = helper.getStartAfterPadding() + helper.getTotalSpace() / 2; 126 | } else { 127 | containerCenter = helper.getEnd() / 2; 128 | } 129 | 130 | return childCenter - containerCenter; 131 | } 132 | 133 | @Nullable 134 | private View findCenterView(RecyclerView.LayoutManager layoutManager, OrientationHelper helper) { 135 | int childCount = layoutManager.getChildCount(); 136 | if (childCount == 0) { 137 | return null; 138 | } else { 139 | View closestChild = null; 140 | int center; 141 | if (layoutManager.getClipToPadding()) { 142 | center = helper.getStartAfterPadding() + helper.getTotalSpace() / 2; 143 | } else { 144 | center = helper.getEnd() / 2; 145 | } 146 | int absClosest = 2147483647; 147 | 148 | for (int i = 0; i < childCount; ++i) { 149 | View child = layoutManager.getChildAt(i); 150 | int childCenter = helper.getDecoratedStart(child) + helper.getDecoratedMeasurement(child) / 2; 151 | int absDistance = Math.abs(childCenter - center); 152 | if (absDistance < absClosest) { 153 | absClosest = absDistance; 154 | closestChild = child; 155 | } 156 | } 157 | 158 | return closestChild; 159 | } 160 | } 161 | 162 | @Nullable 163 | private View findStartView(RecyclerView.LayoutManager layoutManager, OrientationHelper helper) { 164 | int childCount = layoutManager.getChildCount(); 165 | if (childCount == 0) { 166 | return null; 167 | } else { 168 | View closestChild = null; 169 | int startest = 2147483647; 170 | 171 | for (int i = 0; i < childCount; ++i) { 172 | View child = layoutManager.getChildAt(i); 173 | int childStart = helper.getDecoratedStart(child); 174 | if (childStart < startest) { 175 | startest = childStart; 176 | closestChild = child; 177 | } 178 | } 179 | 180 | return closestChild; 181 | } 182 | } 183 | 184 | @NonNull 185 | private OrientationHelper getVerticalHelper(@NonNull RecyclerView.LayoutManager layoutManager) { 186 | RecyclerView.LayoutManager mLayoutManager = null; 187 | if (mVerticalHelper != null) { 188 | mLayoutManager = ReflectUtils.reflect(mVerticalHelper).field("mLayoutManager").get(); 189 | } 190 | if (this.mVerticalHelper == null || mLayoutManager != layoutManager) { 191 | this.mVerticalHelper = OrientationHelper.createVerticalHelper(layoutManager); 192 | } 193 | 194 | return this.mVerticalHelper; 195 | } 196 | 197 | @NonNull 198 | private OrientationHelper getHorizontalHelper(@NonNull RecyclerView.LayoutManager layoutManager) { 199 | RecyclerView.LayoutManager mLayoutManager = null; 200 | if (mHorizontalHelper != null) { 201 | mLayoutManager = ReflectUtils.reflect(mHorizontalHelper).field("mLayoutManager").get(); 202 | } 203 | if (this.mHorizontalHelper == null || mLayoutManager != layoutManager) { 204 | this.mHorizontalHelper = OrientationHelper.createHorizontalHelper(layoutManager); 205 | } 206 | 207 | return this.mHorizontalHelper; 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/utils/layoutmanager/PageLayoutManager.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview.utils.layoutmanager; 2 | 3 | import android.content.Context; 4 | import android.view.View; 5 | 6 | import androidx.recyclerview.widget.LinearLayoutManager; 7 | import androidx.recyclerview.widget.RecyclerView; 8 | import androidx.recyclerview.widget.SnapHelper; 9 | 10 | /** 11 | * Date: 2021/1/27 12 | * Author: Yang 13 | * Describe: 14 | */ 15 | public class PageLayoutManager extends LinearLayoutManager { 16 | 17 | private final String TAG = this.getClass().getSimpleName(); 18 | 19 | private RecyclerView mRecyclerView; 20 | private SnapHelper mPagerSnapHelper; 21 | private PagerChangedListener mOnViewPagerListener; 22 | private int mDrift; // 位移,用来判断移动方向 23 | 24 | public PageLayoutManager(Context context, int orientation) { 25 | super(context, orientation, false); 26 | init(); 27 | } 28 | 29 | public PageLayoutManager(Context context, int orientation, boolean reverseLayout) { 30 | super(context, orientation, reverseLayout); 31 | init(); 32 | } 33 | 34 | private void init() { 35 | mPagerSnapHelper = new MyPagerSnapHelper(); 36 | } 37 | 38 | @Override 39 | public void onAttachedToWindow(RecyclerView view) { 40 | super.onAttachedToWindow(view); 41 | mRecyclerView = view; 42 | mPagerSnapHelper.attachToRecyclerView(view); 43 | mRecyclerView.addOnChildAttachStateChangeListener(mChildAttachStateChangeListener); 44 | } 45 | 46 | @Override 47 | public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { 48 | super.onLayoutChildren(recycler, state); 49 | } 50 | 51 | /** 52 | * 滑动状态的改变 53 | * 缓慢拖拽-> SCROLL_STATE_DRAGGING 54 | * 快速滚动-> SCROLL_STATE_SETTLING 55 | * 空闲状态-> SCROLL_STATE_IDLE 56 | */ 57 | @Override 58 | public void onScrollStateChanged(int state) { 59 | switch (state) { 60 | case RecyclerView.SCROLL_STATE_IDLE: 61 | View view = mPagerSnapHelper.findSnapView(this); 62 | if (view == null) return; 63 | int position = getPosition(view); 64 | if (mOnViewPagerListener != null && getChildCount() == 1) { 65 | mOnViewPagerListener.onPageSelected(position, position == getItemCount() - 1); 66 | } 67 | break; 68 | } 69 | } 70 | 71 | /** 监听竖直方向的相对偏移量 */ 72 | @Override 73 | public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) { 74 | this.mDrift = dy; 75 | return super.scrollVerticallyBy(dy, recycler, state); 76 | } 77 | 78 | 79 | /** 监听水平方向的相对偏移量 */ 80 | @Override 81 | public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) { 82 | this.mDrift = dx; 83 | return super.scrollHorizontallyBy(dx, recycler, state); 84 | } 85 | 86 | /** 设置监听 */ 87 | public void setOnPagerChangeListener(PagerChangedListener listener) { 88 | this.mOnViewPagerListener = listener; 89 | } 90 | 91 | private RecyclerView.OnChildAttachStateChangeListener mChildAttachStateChangeListener 92 | = new RecyclerView.OnChildAttachStateChangeListener() { 93 | 94 | @Override 95 | public void onChildViewAttachedToWindow(View view) { 96 | if (mOnViewPagerListener != null && getChildCount() == 1) { 97 | mOnViewPagerListener.onInitComplete(); 98 | } 99 | } 100 | 101 | @Override 102 | public void onChildViewDetachedFromWindow(View view) { 103 | if (mDrift >= 0) { 104 | if (mOnViewPagerListener != null) 105 | mOnViewPagerListener.onPageRelease(true, getPosition(view)); 106 | } else { 107 | if (mOnViewPagerListener != null) 108 | mOnViewPagerListener.onPageRelease(false, getPosition(view)); 109 | } 110 | } 111 | }; 112 | 113 | /** 获取当前的页面下标 */ 114 | public int getCurrentPosition() { 115 | View view = mPagerSnapHelper.findSnapView(this); 116 | return view == null ? -1 : getPosition(view); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/utils/layoutmanager/PagerChangedListener.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview.utils.layoutmanager; 2 | 3 | public interface PagerChangedListener { 4 | 5 | /* 初始化完成 */ 6 | void onInitComplete(); 7 | 8 | /* 释放的监听 */ 9 | void onPageRelease(boolean isNext, int position); 10 | 11 | /* 选中的监听以及判断是否滑动到底部 */ 12 | void onPageSelected(int position, boolean isBottom); 13 | } 14 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/widget/AbsControllerBar.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview.widget; 2 | 3 | import android.content.Context; 4 | import android.util.AttributeSet; 5 | import android.view.View; 6 | import android.widget.FrameLayout; 7 | 8 | import androidx.annotation.NonNull; 9 | import androidx.annotation.Nullable; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | /** 15 | * Date: 2021/3/29 16 | * Author: Yang 17 | * Describe: 18 | */ 19 | public abstract class AbsControllerBar extends FrameLayout implements IPDFController { 20 | 21 | 22 | protected List mListener; 23 | 24 | public AbsControllerBar(@NonNull Context context) { 25 | this(context, null); 26 | } 27 | 28 | public AbsControllerBar(@NonNull Context context, @Nullable AttributeSet attrs) { 29 | this(context, attrs, 0); 30 | } 31 | 32 | public AbsControllerBar(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 33 | super(context, attrs, defStyleAttr); 34 | initView(context); 35 | } 36 | 37 | protected abstract View getView(); 38 | 39 | public void setPreviousText(String previousText) { 40 | 41 | } 42 | 43 | public void setNextText(String nextText) { 44 | 45 | } 46 | 47 | 48 | private void initView(Context context) { 49 | View view = getView(); 50 | if (view == null) { 51 | return; 52 | } 53 | addView(view); 54 | mListener = new ArrayList<>(); 55 | } 56 | 57 | protected void clickPrevious() { 58 | for (OperateListener listener : mListener) { 59 | if (listener != null) { 60 | listener.clickPrevious(); 61 | } 62 | } 63 | } 64 | 65 | protected void clickNext() { 66 | for (OperateListener listener : mListener) { 67 | if (listener != null) { 68 | listener.clickNext(); 69 | } 70 | } 71 | } 72 | 73 | @Override 74 | public void addOperateListener(OperateListener listener) { 75 | if (mListener != null && listener != null) { 76 | mListener.add(listener); 77 | } 78 | } 79 | 80 | @Override 81 | public void setPageIndexText(String text) { 82 | 83 | } 84 | 85 | @Override 86 | protected void onDetachedFromWindow() { 87 | super.onDetachedFromWindow(); 88 | if (mListener != null) { 89 | mListener.clear(); 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/widget/IPDFController.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview.widget; 2 | 3 | /** 4 | * Date: 2021/3/19 5 | * Author: Yang 6 | * Describe: PDF控制栏接口 7 | */ 8 | public interface IPDFController { 9 | 10 | void addOperateListener(OperateListener listener); 11 | 12 | void setPageIndexText(String text); 13 | 14 | interface OperateListener { 15 | 16 | void clickPrevious(); 17 | 18 | void clickNext(); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/widget/LoadingView.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview.widget; 2 | 3 | import android.content.Context; 4 | import android.graphics.Canvas; 5 | import android.graphics.Color; 6 | import android.graphics.Paint; 7 | import android.graphics.SweepGradient; 8 | import android.util.AttributeSet; 9 | import android.view.View; 10 | import android.view.animation.LinearInterpolator; 11 | import android.view.animation.RotateAnimation; 12 | 13 | public class LoadingView extends View { 14 | 15 | private int strokeWidth; 16 | private int startColor; 17 | private int endColor; 18 | private int duration; 19 | private Paint paint; 20 | private float cx; 21 | private float cy; 22 | private float radius; 23 | private SweepGradient sweepGradient; 24 | 25 | public LoadingView(Context context) { 26 | super(context); 27 | init(); 28 | } 29 | 30 | public LoadingView(Context context, AttributeSet attrs) { 31 | super(context, attrs); 32 | init(); 33 | } 34 | 35 | public LoadingView(Context context, AttributeSet attrs, int defStyleAttr) { 36 | super(context, attrs, defStyleAttr); 37 | init(); 38 | } 39 | 40 | private int dp(int dp) { 41 | return (int) ((float) dp * this.getResources().getDisplayMetrics().density + 0.5F); 42 | } 43 | 44 | private void init() { 45 | strokeWidth = dp(2); 46 | startColor = Color.TRANSPARENT; 47 | endColor = Color.parseColor("#d8d5d8"); 48 | duration = 1200; 49 | 50 | paint = new Paint(Paint.ANTI_ALIAS_FLAG); 51 | paint.setStrokeWidth(strokeWidth); 52 | paint.setStyle(Paint.Style.STROKE); 53 | paint.setStrokeCap(Paint.Cap.ROUND); 54 | paint.setStrokeJoin(Paint.Join.ROUND); 55 | } 56 | 57 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 58 | super.onMeasure(widthMeasureSpec, heightMeasureSpec); 59 | cx = getMeasuredWidth() / 2f; 60 | cy = getMeasuredHeight() / 2f; 61 | radius = this.getMeasuredWidth() / 2f - this.strokeWidth / 2f; 62 | sweepGradient = new SweepGradient(cx, cy, new int[]{startColor, endColor}, null); 63 | } 64 | 65 | protected void onDraw(Canvas canvas) { 66 | super.onDraw(canvas); 67 | paint.setShader(sweepGradient); 68 | canvas.drawCircle(cx, cy, radius, paint); 69 | } 70 | 71 | @Override 72 | protected void onAttachedToWindow() { 73 | super.onAttachedToWindow(); 74 | RotateAnimation animation = new RotateAnimation(0.0F, 359.0F, 1, 0.5F, 1, 0.5F); 75 | animation.setDuration(duration); 76 | animation.setRepeatCount(-1); 77 | animation.setInterpolator(new LinearInterpolator()); 78 | startAnimation(animation); 79 | } 80 | 81 | @Override 82 | protected void onDetachedFromWindow() { 83 | clearAnimation(); 84 | super.onDetachedFromWindow(); 85 | } 86 | } -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/widget/PDFControllerBar.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview.widget; 2 | 3 | import android.content.Context; 4 | import android.graphics.Color; 5 | import android.graphics.Typeface; 6 | import android.os.Build; 7 | import android.util.AttributeSet; 8 | import android.util.TypedValue; 9 | import android.view.View; 10 | import android.view.ViewGroup; 11 | import android.widget.Button; 12 | import android.widget.LinearLayout; 13 | import android.widget.TextView; 14 | 15 | import androidx.annotation.Nullable; 16 | 17 | import com.zjy.pdfview.R; 18 | 19 | import static android.view.Gravity.CENTER; 20 | import static android.widget.LinearLayout.HORIZONTAL; 21 | 22 | /** 23 | * Date: 2021/3/19 24 | * Author: Yang 25 | * Describe: PDF控制栏视图 26 | */ 27 | public class PDFControllerBar extends AbsControllerBar implements View.OnClickListener { 28 | 29 | private Button previousBtn, nextBtn; 30 | private TextView pageIndexTv; 31 | 32 | public PDFControllerBar(Context context) { 33 | this(context, null); 34 | } 35 | 36 | public PDFControllerBar(Context context, @Nullable AttributeSet attrs) { 37 | this(context, attrs, 0); 38 | } 39 | 40 | public PDFControllerBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 41 | super(context, attrs, defStyleAttr); 42 | } 43 | 44 | @Override 45 | public View getView() { 46 | LinearLayout rootView= new LinearLayout(getContext()); 47 | rootView.setOrientation(HORIZONTAL); 48 | rootView.setGravity(CENTER); 49 | setBackgroundColor(Color.WHITE); 50 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 51 | setElevation(dip2px(getContext(), 8)); 52 | } 53 | 54 | previousBtn = new Button(getContext()); 55 | previousBtn.setBackgroundResource(R.drawable.bg_operate_btn); 56 | previousBtn.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14); 57 | previousBtn.setText("上一页"); 58 | rootView.addView(previousBtn, new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, dip2px(getContext(), 36))); 59 | 60 | pageIndexTv = new TextView(getContext()); 61 | pageIndexTv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15); 62 | pageIndexTv.setPadding(dip2px(getContext(), 16), 0, dip2px(getContext(), 16), 0); 63 | rootView.addView(pageIndexTv, new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 64 | pageIndexTv.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); 65 | pageIndexTv.setText("1/1"); 66 | 67 | nextBtn = new Button(getContext()); 68 | nextBtn.setBackgroundResource(R.drawable.bg_operate_btn); 69 | nextBtn.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14); 70 | nextBtn.setText("下一页"); 71 | rootView.addView(nextBtn, new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, dip2px(getContext(), 36))); 72 | 73 | previousBtn.setOnClickListener(this); 74 | nextBtn.setOnClickListener(this); 75 | return rootView; 76 | } 77 | 78 | @Override 79 | public void onClick(View view) { 80 | if (view == previousBtn) { 81 | clickPrevious(); 82 | } else if (view == nextBtn) { 83 | clickNext(); 84 | } 85 | } 86 | 87 | @Override 88 | public void setPreviousText(String previousText) { 89 | if (previousBtn != null && previousText != null) { 90 | previousBtn.setText(previousText); 91 | } 92 | } 93 | 94 | @Override 95 | public void setNextText(String nextText) { 96 | if (nextBtn != null && nextText != null) { 97 | nextBtn.setText(nextText); 98 | } 99 | } 100 | 101 | private static int dip2px(Context context, float dpValue) { 102 | final float scale = context.getResources().getDisplayMetrics().density; 103 | return (int) (dpValue * scale + 0.5f); 104 | } 105 | 106 | @Override 107 | public void setPageIndexText(String text) { 108 | if (pageIndexTv != null && text != null) { 109 | pageIndexTv.setText(text); 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/widget/PdfLoadingLayout.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview.widget; 2 | 3 | import android.content.Context; 4 | import android.util.AttributeSet; 5 | import android.view.LayoutInflater; 6 | import android.view.View; 7 | import android.widget.Button; 8 | import android.widget.FrameLayout; 9 | import android.widget.TextView; 10 | 11 | import androidx.annotation.NonNull; 12 | import androidx.annotation.Nullable; 13 | 14 | import com.zjy.pdfview.R; 15 | import com.zjy.pdfview.utils.PdfLog; 16 | 17 | /** 18 | * Date: 2021/1/27 19 | * Author: Yang 20 | * Describe: 21 | */ 22 | public class PdfLoadingLayout extends FrameLayout { 23 | 24 | TextView waitTv; 25 | Button reloadTv; 26 | View waitLayout; 27 | LoadLayoutListener mListener; 28 | 29 | public PdfLoadingLayout(@NonNull Context context) { 30 | this(context, null); 31 | } 32 | 33 | public PdfLoadingLayout(@NonNull Context context, @Nullable AttributeSet attrs) { 34 | this(context, attrs, 0); 35 | } 36 | 37 | public PdfLoadingLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 38 | super(context, attrs, defStyleAttr); 39 | init(); 40 | } 41 | 42 | private void init() { 43 | LayoutInflater.from(getContext()).inflate(R.layout.layout_pdf_loading, this); 44 | 45 | waitTv = findViewById(R.id.waiting_tv); 46 | reloadTv = findViewById(R.id.reload_tv); 47 | waitLayout = findViewById(R.id.waiting_layout); 48 | 49 | reloadTv.setOnClickListener(new OnClickListener() { 50 | @Override 51 | public void onClick(View v) { 52 | if (mListener != null) { 53 | mListener.clickRetry(); 54 | } 55 | } 56 | }); 57 | } 58 | 59 | 60 | public void showLoading() { 61 | PdfLog.logDebug("showLoading"); 62 | setVisibility(VISIBLE); 63 | waitTv.setText("加载中"); 64 | reloadTv.setVisibility(GONE); 65 | } 66 | 67 | public void showContent() { 68 | PdfLog.logDebug("showContent"); 69 | setVisibility(GONE); 70 | } 71 | 72 | public void showFail() { 73 | setVisibility(VISIBLE); 74 | waitTv.setText("加载失败"); 75 | waitLayout.setVisibility(GONE); 76 | reloadTv.setVisibility(VISIBLE); 77 | } 78 | 79 | public void setLoadLayoutListener(LoadLayoutListener listener) { 80 | mListener = listener; 81 | } 82 | 83 | public interface LoadLayoutListener { 84 | void clickRetry(); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/widget/PdfRecyclerView.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview.widget; 2 | 3 | import android.content.Context; 4 | 5 | import android.util.AttributeSet; 6 | import android.view.MotionEvent; 7 | 8 | import androidx.annotation.NonNull; 9 | import androidx.annotation.Nullable; 10 | import androidx.recyclerview.widget.RecyclerView; 11 | 12 | /** 13 | * Date: 2021/1/27 14 | * Author: Yang 15 | * Describe: 16 | */ 17 | public class PdfRecyclerView extends RecyclerView { 18 | public PdfRecyclerView(@NonNull Context context) { 19 | super(context); 20 | } 21 | 22 | public PdfRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) { 23 | super(context, attrs); 24 | } 25 | 26 | public PdfRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) { 27 | super(context, attrs, defStyle); 28 | } 29 | 30 | 31 | @Override 32 | public boolean onInterceptTouchEvent(MotionEvent e) { 33 | return false; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/widget/ScaleImageView.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview.widget; 2 | 3 | import android.content.Context; 4 | import android.graphics.Bitmap; 5 | import android.graphics.Color; 6 | import android.graphics.Matrix; 7 | import android.graphics.PointF; 8 | import android.util.AttributeSet; 9 | import android.view.GestureDetector; 10 | import android.view.MotionEvent; 11 | import android.view.View; 12 | 13 | import androidx.annotation.Nullable; 14 | import androidx.appcompat.widget.AppCompatImageView; 15 | 16 | /** 17 | * Date: 2021/1/27 18 | * Author: Yang 19 | * Describe: 20 | */ 21 | public class ScaleImageView extends AppCompatImageView { 22 | 23 | private MatrixTouchListener mListener; 24 | 25 | public ScaleImageView(Context context) { 26 | this(context, null); 27 | } 28 | 29 | public ScaleImageView(Context context, @Nullable AttributeSet attrs) { 30 | this(context, attrs, 0); 31 | } 32 | 33 | public ScaleImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 34 | super(context, attrs, defStyleAttr); 35 | mListener = new MatrixTouchListener(); 36 | setOnTouchListener(mListener); 37 | mGestureDetector = new GestureDetector(getContext(), new GestureListener(mListener)); 38 | setBackgroundColor(Color.WHITE); 39 | //将缩放类型设置为FIT_CENTER,表示把图片按比例扩大/缩小到View的宽度,居中显示 40 | setScaleType(ScaleType.FIT_CENTER); 41 | } 42 | 43 | private GestureDetector mGestureDetector; 44 | /** 45 | * 模板Matrix,用以初始化 46 | */ 47 | private Matrix mMatrix = new Matrix(); 48 | /** 49 | * 图片长度 50 | */ 51 | private float mImageWidth; 52 | /** 53 | * 图片高度 54 | */ 55 | private float mImageHeight; 56 | 57 | @Override 58 | public void setImageBitmap(Bitmap bm) { 59 | // TODO Auto-generated method stub 60 | super.setImageBitmap(bm); 61 | setScaleType(ScaleType.FIT_CENTER); 62 | mMatrix.reset(); 63 | float[] values = new float[9]; 64 | mMatrix.getValues(values); 65 | 66 | //setImageMatrix(mMatrix); 67 | mListener.resetListener(); 68 | //图片宽度为屏幕宽度除缩放倍数 69 | mImageWidth = bm.getWidth() / values[Matrix.MSCALE_X]; 70 | mImageHeight = (bm.getHeight() - values[Matrix.MTRANS_Y] * 2) / values[Matrix.MSCALE_Y]; 71 | } 72 | 73 | public void resetScale(int scale) { 74 | //mMatrix.reset(); 75 | //mListener.resetListener(scale); 76 | } 77 | 78 | public class MatrixTouchListener implements OnTouchListener { 79 | /** 80 | * 拖拉照片模式 81 | */ 82 | private static final int MODE_DRAG = 1; 83 | /** 84 | * 放大缩小照片模式 85 | */ 86 | private static final int MODE_ZOOM = 2; 87 | /** 88 | * 不支持Matrix 89 | */ 90 | private static final int MODE_UNABLE = 3; 91 | /** 92 | * 最大缩放级别 93 | */ 94 | float mMaxScale = 6; 95 | /** 96 | * 双击时的缩放级别 97 | */ 98 | float mDoubleClickScale = 2; 99 | private int mMode = 0;// 100 | /** 101 | * 缩放开始时的手指间距 102 | */ 103 | private float mStartDis; 104 | /** 105 | * 当前Matrix 106 | */ 107 | private Matrix mCurrentMatrix = new Matrix(); 108 | 109 | /** 110 | * 用于记录开始时候的坐标位置 111 | */ 112 | private PointF startPoint = new PointF(); 113 | 114 | public void resetListener() { 115 | mStartDis = 0; 116 | mCurrentMatrix.reset(); 117 | startPoint.set(0, 0); 118 | mCurrentMatrix.setScale(1, 1); 119 | setImageMatrix(mCurrentMatrix); 120 | } 121 | 122 | @Override 123 | public boolean onTouch(View v, MotionEvent event) { 124 | // TODO Auto-generated method stub 125 | switch (event.getActionMasked()) { 126 | case MotionEvent.ACTION_DOWN: 127 | //设置拖动模式 128 | mMode = MODE_DRAG; 129 | startPoint.set(event.getX(), event.getY()); 130 | isMatrixEnable(); 131 | break; 132 | case MotionEvent.ACTION_UP: 133 | case MotionEvent.ACTION_CANCEL: 134 | reSetMatrix(); 135 | break; 136 | case MotionEvent.ACTION_MOVE: 137 | if (mMode == MODE_ZOOM) { 138 | setZoomMatrix(event); 139 | } else if (mMode == MODE_DRAG) { 140 | setDragMatrix(event); 141 | } 142 | break; 143 | case MotionEvent.ACTION_POINTER_DOWN: 144 | if (mMode == MODE_UNABLE) return true; 145 | mMode = MODE_ZOOM; 146 | mStartDis = distance(event); 147 | break; 148 | default: 149 | break; 150 | } 151 | 152 | return mGestureDetector.onTouchEvent(event); 153 | } 154 | 155 | public void setDragMatrix(MotionEvent event) { 156 | if (isZoomChanged()) { 157 | float dx = event.getX() - startPoint.x; // 得到x轴的移动距离 158 | float dy = event.getY() - startPoint.y; // 得到x轴的移动距离 159 | //避免和双击冲突,大于10f才算是拖动 160 | if (Math.sqrt(dx * dx + dy * dy) > 10f) { 161 | startPoint.set(event.getX(), event.getY()); 162 | //在当前基础上移动 163 | mCurrentMatrix.set(getImageMatrix()); 164 | float[] values = new float[9]; 165 | mCurrentMatrix.getValues(values); 166 | dx = checkDxBound(values, dx); 167 | dy = checkDyBound(values, dy); 168 | mCurrentMatrix.postTranslate(dx, dy); 169 | setImageMatrix(mCurrentMatrix); 170 | } 171 | } 172 | } 173 | 174 | /** 175 | * 判断缩放级别是否是改变过 176 | * 177 | * @return true表示非初始值, false表示初始值 178 | */ 179 | private boolean isZoomChanged() { 180 | float[] values = new float[9]; 181 | getImageMatrix().getValues(values); 182 | //获取当前X轴缩放级别 183 | float scale = values[Matrix.MSCALE_X]; 184 | //获取模板的X轴缩放级别,两者做比较 185 | mMatrix.getValues(values); 186 | return scale != values[Matrix.MSCALE_X]; 187 | } 188 | 189 | /** 190 | * 和当前矩阵对比,检验dy,使图像移动后不会超出ImageView边界 191 | * 192 | * @param values 193 | * @param dy 194 | * @return 195 | */ 196 | private float checkDyBound(float[] values, float dy) { 197 | float height = getHeight(); 198 | if (mImageHeight * values[Matrix.MSCALE_Y] < height) 199 | return 0; 200 | if (values[Matrix.MTRANS_Y] + dy > 0) 201 | dy = -values[Matrix.MTRANS_Y]; 202 | else if (values[Matrix.MTRANS_Y] + dy < -(mImageHeight * values[Matrix.MSCALE_Y] - height)) 203 | dy = -(mImageHeight * values[Matrix.MSCALE_Y] - height) - values[Matrix.MTRANS_Y]; 204 | return dy; 205 | } 206 | 207 | /** 208 | * 和当前矩阵对比,检验dx,使图像移动后不会超出ImageView边界 209 | * 210 | * @param values 211 | * @param dx 212 | * @return 213 | */ 214 | private float checkDxBound(float[] values, float dx) { 215 | float width = getWidth(); 216 | if (mImageWidth * values[Matrix.MSCALE_X] < width) 217 | return 0; 218 | if (values[Matrix.MTRANS_X] + dx > 0) 219 | dx = -values[Matrix.MTRANS_X]; 220 | else if (values[Matrix.MTRANS_X] + dx < -(mImageWidth * values[Matrix.MSCALE_X] - width)) 221 | dx = -(mImageWidth * values[Matrix.MSCALE_X] - width) - values[Matrix.MTRANS_X]; 222 | return dx; 223 | } 224 | 225 | /** 226 | * 设置缩放Matrix 227 | * 228 | * @param event 229 | */ 230 | private void setZoomMatrix(MotionEvent event) { 231 | //只有同时触屏两个点的时候才执行 232 | if (event.getPointerCount() < 2) return; 233 | float endDis = distance(event);// 结束距离 234 | if (endDis > 10f) { // 两个手指并拢在一起的时候像素大于10 235 | float scale = endDis / mStartDis;// 得到缩放倍数 236 | mStartDis = endDis;//重置距离 237 | mCurrentMatrix.set(getImageMatrix());//初始化Matrix 238 | float[] values = new float[9]; 239 | mCurrentMatrix.getValues(values); 240 | 241 | scale = checkMaxScale(scale, values); 242 | setImageMatrix(mCurrentMatrix); 243 | } 244 | } 245 | 246 | /** 247 | * 检验scale,使图像缩放后不会超出最大倍数 248 | * 249 | * @param scale 250 | * @param values 251 | * @return 252 | */ 253 | private float checkMaxScale(float scale, float[] values) { 254 | if (scale * values[Matrix.MSCALE_X] > mMaxScale) 255 | scale = mMaxScale / values[Matrix.MSCALE_X]; 256 | mCurrentMatrix.postScale(scale, scale, getWidth() / 2, getHeight() / 2); 257 | return scale; 258 | } 259 | 260 | /** 261 | * 重置Matrix 262 | */ 263 | private void reSetMatrix() { 264 | if (checkRest()) { 265 | setScaleType(ScaleType.FIT_CENTER); 266 | mCurrentMatrix.set(mMatrix); 267 | setImageMatrix(mCurrentMatrix); 268 | } 269 | } 270 | 271 | /** 272 | * 判断是否需要重置 273 | * 274 | * @return 当前缩放级别小于模板缩放级别时,重置 275 | */ 276 | private boolean checkRest() { 277 | // TODO Auto-generated method stub 278 | float[] values = new float[9]; 279 | getImageMatrix().getValues(values); 280 | //获取当前X轴缩放级别 281 | float scale = values[Matrix.MSCALE_X]; 282 | //获取模板的X轴缩放级别,两者做比较 283 | mMatrix.getValues(values); 284 | return scale < values[Matrix.MSCALE_X]; 285 | } 286 | 287 | /** 288 | * 判断是否支持Matrix 289 | */ 290 | private void isMatrixEnable() { 291 | //当加载出错时,不可缩放 292 | if (getScaleType() != ScaleType.CENTER) { 293 | setScaleType(ScaleType.MATRIX); 294 | } else { 295 | mMode = MODE_UNABLE;//设置为不支持手势 296 | } 297 | } 298 | 299 | /** 300 | * 计算两个手指间的距离 301 | * 302 | * @param event 303 | * @return 304 | */ 305 | private float distance(MotionEvent event) { 306 | float dx = event.getX(1) - event.getX(0); 307 | float dy = event.getY(1) - event.getY(0); 308 | /** 使用勾股定理返回两点之间的距离 */ 309 | return (float) Math.sqrt(dx * dx + dy * dy); 310 | } 311 | 312 | /** 313 | * 双击时触发 314 | */ 315 | public void onDoubleClick() { 316 | float scale = isZoomChanged() ? 1 : mDoubleClickScale; 317 | mCurrentMatrix.set(mMatrix);//初始化Matrix 318 | mCurrentMatrix.postScale(scale, scale, getWidth() / 2, getHeight() / 2); 319 | setImageMatrix(mCurrentMatrix); 320 | } 321 | } 322 | 323 | 324 | private class GestureListener extends GestureDetector.SimpleOnGestureListener { 325 | private final MatrixTouchListener listener; 326 | 327 | public GestureListener(MatrixTouchListener listener) { 328 | this.listener = listener; 329 | } 330 | 331 | @Override 332 | public boolean onDown(MotionEvent e) { 333 | //捕获Down事件 334 | return true; 335 | } 336 | 337 | @Override 338 | public boolean onDoubleTap(MotionEvent e) { 339 | //触发双击事件 340 | listener.onDoubleClick(); 341 | return true; 342 | } 343 | 344 | @Override 345 | public boolean onSingleTapUp(MotionEvent e) { 346 | // TODO Auto-generated method stub 347 | return super.onSingleTapUp(e); 348 | } 349 | 350 | @Override 351 | public void onLongPress(MotionEvent e) { 352 | // TODO Auto-generated method stub 353 | super.onLongPress(e); 354 | } 355 | 356 | @Override 357 | public boolean onScroll(MotionEvent e1, MotionEvent e2, 358 | float distanceX, float distanceY) { 359 | return super.onScroll(e1, e2, distanceX, distanceY); 360 | } 361 | 362 | @Override 363 | public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, 364 | float velocityY) { 365 | // TODO Auto-generated method stub 366 | 367 | return super.onFling(e1, e2, velocityX, velocityY); 368 | } 369 | 370 | @Override 371 | public void onShowPress(MotionEvent e) { 372 | // TODO Auto-generated method stub 373 | super.onShowPress(e); 374 | } 375 | 376 | 377 | @Override 378 | public boolean onDoubleTapEvent(MotionEvent e) { 379 | // TODO Auto-generated method stub 380 | return super.onDoubleTapEvent(e); 381 | } 382 | 383 | @Override 384 | public boolean onSingleTapConfirmed(MotionEvent e) { 385 | // TODO Auto-generated method stub 386 | return super.onSingleTapConfirmed(e); 387 | } 388 | 389 | } 390 | } 391 | -------------------------------------------------------------------------------- /pdfview/src/main/java/com/zjy/pdfview/widget/ScrollSlider.java: -------------------------------------------------------------------------------- 1 | package com.zjy.pdfview.widget; 2 | 3 | import android.content.Context; 4 | import android.graphics.Color; 5 | import android.util.AttributeSet; 6 | import android.util.Log; 7 | import android.view.MotionEvent; 8 | import android.view.View; 9 | import android.widget.ImageView; 10 | import android.widget.LinearLayout; 11 | 12 | import androidx.annotation.Nullable; 13 | 14 | import com.zjy.pdfview.R; 15 | 16 | import static android.view.Gravity.CENTER; 17 | 18 | public class ScrollSlider extends LinearLayout { 19 | 20 | private float slideDownY; 21 | private ScrollSlideListener listener; 22 | 23 | public ScrollSlider(Context context) { 24 | this(context, null); 25 | } 26 | 27 | public ScrollSlider(Context context, @Nullable AttributeSet attrs) { 28 | this(context, attrs, 0); 29 | } 30 | 31 | public ScrollSlider(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 32 | super(context, attrs, defStyleAttr); 33 | init(); 34 | } 35 | 36 | private void init() { 37 | setOrientation(VERTICAL); 38 | setBackgroundColor(Color.parseColor("#7D000000")); 39 | setGravity(CENTER); 40 | ImageView topArrow = new ImageView(getContext()); 41 | topArrow.setImageResource(R.drawable.ic_top_arrow); 42 | addView(topArrow); 43 | 44 | ImageView bottomArrow = new ImageView(getContext()); 45 | bottomArrow.setImageResource(R.drawable.ic_top_arrow); 46 | bottomArrow.setRotation(180f); 47 | addView(bottomArrow); 48 | 49 | ((LayoutParams)bottomArrow.getLayoutParams()).topMargin = 20; 50 | } 51 | 52 | @Override 53 | protected void onSizeChanged(int w, int h, int oldw, int oldh) { 54 | super.onSizeChanged(w, h, oldw, oldh); 55 | for (int i=0; i 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /pdfview/src/main/res/layout/activity_pdfrenderer.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 17 | 29 | 38 | 39 | 40 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /pdfview/src/main/res/layout/layout_page_item.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 13 | 14 | -------------------------------------------------------------------------------- /pdfview/src/main/res/layout/layout_pdf_loading.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 14 | 18 | 25 | 26 | 27 |