同样使用网上流行的类库
1、添加依赖(在你的module中不是project中),添加后别忘记同步
//pdf
compile 'com.github.barteksc:android-pdf-viewer:2.6.1'
2、使用在xml文件中添加该布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.mazhan.android_fundfriend.activitys.LoadPDFActivity">
<com.github.barteksc.pdfviewer.PDFView
android:id="@+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
3、实现
package com.mazhan.android_fundfriend.activitys;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.mazhan.android_fundfriend.R;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* 显示PDF的页面
*/
public class LoadPDFActivity extends AppCompatActivity {
private static final String TAG = "LoadPDFActivity--TAG:";
private PDFView pdfView;
private String path;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_load_pdf);
pdfView = findViewById(R.id.pdfView);
path = getIntent().getStringExtra("url");
if (!TextUtils.isEmpty(path)) {
new LoadPdfThread().start();
}
}
class LoadPdfThread extends Thread {
@Override
public void run() {
super.run();
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (connection.getResponseCode() == 200) {
final InputStream inputStream = connection.getInputStream();
//主线程更新界面
runOnUiThread(new Runnable() {
@Override
public void run() {
if (inputStream != null) {
pdfView.fromStream(inputStream).defaultPage(0)//默认页面
.enableDoubletap(true)
.swipeHorizontal(true)//是不是横向查看
.onPageChange(new OnPageChangeListener() {
@Override
public void onPageChanged(int page, int pageCount) {
}
})
.enableSwipe(true)
.load();
}
}
});
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
我这里没有处理内存泄露,使用了内部类,而且流没有关闭,这里如果直接关闭流,可能导致页面不显示