Android: How to use PDFViewer with Fragments

2.7k views Asked by At

I have a requirement where I need to display PDF file within my Android app. I have used PDFViewer.jar to do so in some of my Activities, which is explained here https://github.com/jblough/Android-Pdf-Viewer-Library . Now I am stuck up with displaying PDF file inside a Fragment. But PDFViewer.jar has been limited to Activity. I have seen the source code of PDFViewer.jar and am unable to convert it for Fragment. Can anyone help me please.

Thanks

2

There are 2 answers

0
Sulaiman Musthofa S On

This is load PDF in fragment use PDFViewer

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
     View v = inflater.inflate(R.layout.fragment_keluarga, container, false); 
     pdfView = (PDFView) v.findViewById(R.id.keluargaPdf); 
     pdfView.fromAsset("tiga.pdf").load();

     // Inflate the layout for this fragment     
     return v;    
}
0
Blusky On

You should take, PdfViewerActivity.java (https://github.com/jblough/Android-Pdf-Viewer-Library/blob/master/src/net/sf/andpdf/pdfviewer/PdfViewerActivity.java), rename it to PdfViewerFragment.java. Change extends Activity to extends Fragment in Android Studio, and correct each red line.

Also, don't forget to import the rest of the project (or you'll have missing classes)

You should especially change each need of Context (this) by getActivity() and findViewById() by getView().findViewById(R.id.foo).

Surely, it won't be enough, but it's a good place to start.