PdfViewerFragment
@RequiresExtension(extension = 31, version = 13)
public class PdfViewerFragment extends Fragment
A Fragment that renders a PDF document.
A [PdfViewerFragment] that can display paginated PDFs. The viewer includes a FAB for annotation support and a search menu. Each page is rendered in its own View. Upon creation, this fragment displays a loading spinner.
Rendering is done in 2 passes:
- Layout: Request the page data, get the dimensions and set them as measure for the image view.
- Render: Create bitmap(s) at adequate dimensions and attach them to the page view.
The layout pass is progressive: starts with a few first pages of the document, then reach further as the user scrolls down (and ultimately spans the whole document). The rendering pass is tightly limited to the currently visible pages. Pages that are scrolled past (become not visible) have their bitmaps released to free up memory.
Note that every activity/fragment that uses this class has to be themed with Theme.AppCompat or a theme that extends that theme.
See also | |
---|---|
documentUri |
Summary
Public constructors |
---|
Protected constructors |
---|
PdfViewerFragment(@NonNull PdfStylingOptions pdfStylingOptions) Protected constructor for instantiating a |
Public methods |
|
---|---|
final Uri |
The URI of the PDF document to display defaulting to |
final boolean |
Controls whether text search mode is active. |
final boolean |
Indicates whether the toolbox should be visible. |
static final @NonNull PdfViewerFragment |
newInstance(@NonNull PdfStylingOptions pdfStylingOptions) Creates a new instance of |
View |
onCreateView( Called to have the fragment instantiate its user interface view. |
void |
Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity. |
void |
onLoadDocumentError(@NonNull Throwable error) Invoked when a problem arises during the loading process of the PDF document. |
void |
Invoked when the document has been fully loaded, processed, and the initial pages are displayed within the viewing area. |
void |
onRequestImmersiveMode(boolean enterImmersive) Called when the PDF view wants to enter or exit immersive mode based on user's interaction with the content. |
void |
onResume() Called when the fragment is visible to the user and actively running. |
void |
onViewCreated(@NonNull View view, Bundle savedInstanceState) Called immediately after |
final void |
setDocumentUri(Uri documentUri) The URI of the PDF document to display defaulting to |
final void |
setTextSearchActive(boolean isTextSearchActive) Controls whether text search mode is active. |
final void |
setToolboxVisible(boolean isToolboxVisible) Indicates whether the toolbox should be visible. |
Inherited methods |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
Public constructors
Protected constructors
PdfViewerFragment
protected PdfViewerFragment(@NonNull PdfStylingOptions pdfStylingOptions)
Protected constructor for instantiating a PdfViewerFragment
with the specified styling options.
Parameters | |
---|---|
@NonNull PdfStylingOptions pdfStylingOptions |
The styling options to be applied to the PDF viewer. |
Public methods
getDocumentUri
public final Uri getDocumentUri()
The URI of the PDF document to display defaulting to null
.
When this property is set, the fragment begins loading the PDF document. A visual indicator is displayed while the document is being loaded. Once the loading is fully completed, the onLoadDocumentSuccess
callback is invoked. If an error occurs during the loading phase, the onLoadDocumentError
callback is invoked with the exception.
Accepts the following URI schemes:
- content ([android.content.ContentResolver.SCHEME_CONTENT])
- file ([android.content.ContentResolver.SCHEME_FILE])
Setting a different URI will cancel any ongoing load operation, reset the fragment's state, and display a loading indicator until the new content is loaded.
If the same URI is set multiple times, the load operation will not be restarted. Instead, the existing load operation will continue.
Throws | |
---|---|
kotlin.IllegalArgumentException |
if the uri is not allowed. |
isTextSearchActive
public final boolean isTextSearchActive()
Controls whether text search mode is active. Defaults to false.
When text search mode is activated, the search menu becomes visible, and search functionality is enabled. Deactivating text search mode hides the search menu, clears search results, and removes any search-related highlights.
Note: This property can only be set after the document has successfully loaded i.e.[onLoadDocumentSuccess] is triggered. Any attempts to change it beforehand will have no effect.
isToolboxVisible
public final boolean isToolboxVisible()
Indicates whether the toolbox should be visible.
The host app can control this property to show/hide the toolbox based on its state and the onRequestImmersiveMode
callback. The setter updates the UI elements within the fragment accordingly.
newInstance
public static final @NonNull PdfViewerFragment newInstance(@NonNull PdfStylingOptions pdfStylingOptions)
Creates a new instance of PdfViewerFragment
with the specified styling options.
Parameters | |
---|---|
@NonNull PdfStylingOptions pdfStylingOptions |
The styling options to be applied. |
Returns | |
---|---|
@NonNull PdfViewerFragment |
A new instance of |
onCreateView
public View onCreateView(
@NonNull LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState
)
Called to have the fragment instantiate its user interface view. This is optional, and non-graphical fragments can return null. This will be called between onCreate
and onViewCreated
.
A default View can be returned by calling Fragment
in your constructor. Otherwise, this method returns null.
It is recommended to only inflate the layout in this method and move logic that operates on the returned View to onViewCreated
.
If you return a View from here, you will later be called in onDestroyView
when the view is being released.
Parameters | |
---|---|
@NonNull LayoutInflater inflater |
The LayoutInflater object that can be used to inflate any views in the fragment, |
ViewGroup container |
If non-null, this is the parent view that the fragment's UI should be attached to. The fragment should not add the view itself, but this can be used to generate the LayoutParams of the view. |
Bundle savedInstanceState |
If non-null, this fragment is being re-constructed from a previous saved state as given here. |
Returns | |
---|---|
View |
Return the View for the fragment's UI, or null. |
onInflate
public void onInflate(
@NonNull Context context,
@NonNull AttributeSet attrs,
Bundle savedInstanceState
)
Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity. This may be called immediately after the fragment is created from a FragmentContainerView
in a layout file. Note this is before the fragment's onAttach
has been called; all you should do here is parse the attributes and save them away.
This is called the first time the fragment is inflated. If it is being inflated into a new instance with saved state, this method will not be called a second time for the restored state fragment.
Here is a typical implementation of a fragment that can take parameters both through attributes supplied here as well from getArguments
:
public static class MyFragment extends Fragment { CharSequence mLabel; /** * Create a new instance of MyFragment that will be initialized * with the given arguments. */ static MyFragment newInstance(CharSequence label) { MyFragment f = new MyFragment(); Bundle b = new Bundle(); b.putCharSequence("label", label); f.setArguments(b); return f; } /** * Parse attributes during inflation from a view hierarchy into the * arguments we handle. */ @Override public void onInflate(@NonNull Context context, @NonNull AttributeSet attrs, @Nullable Bundle savedInstanceState) { super.onInflate(context, attrs, savedInstanceState); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FragmentArguments); mLabel = a.getText(R.styleable.FragmentArguments_android_label); a.recycle(); } /** * During creation, if arguments have been supplied to the fragment * then parse those out. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); if (args != null) { CharSequence label = args.getCharSequence("label"); if (label != null) { mLabel = label; } } } /** * Create the view for this fragment, using the arguments given to it. */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.hello_world, container, false); View tv = v.findViewById(R.id.text); ((TextView)tv).setText(mLabel != null ? mLabel : "(no label)"); ViewCompat.setBackground( tv, ContextCompat.getDrawable(getContext(), android.R.drawable.gallery_thumb)); return v; } }
Note that parsing the XML attributes uses a "styleable" resource. The declaration for the styleable used here is:
<declare-styleable name="FragmentArguments"> <attr name="android:label" /> </declare-styleable>
The fragment can then be declared within its activity's content layout through a tag like this:
<androidx.fragment.app.FragmentContainerView class="com.example.android.supportv4.app.FragmentArgumentsSupport$MyFragment" android:id="@+id/embedded" android:layout_width="0px" android:layout_height="wrap_content" android:layout_weight="1" android:label="@string/fragment_arguments_embedded" />
This fragment can also be created dynamically from arguments given at runtime in the arguments Bundle; here is an example of doing so at creation of the containing activity:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_arguments_support); if (savedInstanceState == null) { // First-time init; create fragment to embed in activity. FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); Fragment newFragment = MyFragment.newInstance("From Arguments"); ft.add(R.id.created, newFragment); ft.commit(); } }
Parameters | |
---|---|
@NonNull Context context |
The Activity that is inflating this fragment. |
@NonNull AttributeSet attrs |
The attributes at the tag where the fragment is being created. |
Bundle savedInstanceState |
If the fragment is being re-created from a previous saved state, this is the state. |
onLoadDocumentError
public void onLoadDocumentError(@NonNull Throwable error)
Invoked when a problem arises during the loading process of the PDF document. This callback provides details about the encountered error, allowing for appropriate error handling and user notification.
Note that this callback is dispatched only when the fragment is fully created and not yet destroyed, i.e., after [onCreate] has fully run and before [onDestroy] runs, and only on the main thread.
onLoadDocumentSuccess
public void onLoadDocumentSuccess()
Invoked when the document has been fully loaded, processed, and the initial pages are displayed within the viewing area. This callback signifies that the document is ready for user interaction.
Note that this callback is dispatched only when the fragment is fully created and not yet destroyed, i.e., after [onCreate] has fully run and before [onDestroy] runs, and only on the main thread.
onRequestImmersiveMode
public void onRequestImmersiveMode(boolean enterImmersive)
Called when the PDF view wants to enter or exit immersive mode based on user's interaction with the content. Apps would typically hide their top bar or other navigational interface when in immersive mode. The default implementation keeps toolbox visibility in sync with the enterImmersive mode. It is recommended that apps keep this behaviour by calling super.onRequestImmersiveMode while overriding this method.
Parameters | |
---|---|
boolean enterImmersive |
true to enter immersive mode, false to exit. |
onResume
public void onResume()
Called when the fragment is visible to the user and actively running. This is generally tied to Activity.onResume
of the containing Activity's lifecycle.
onViewCreated
public void onViewCreated(@NonNull View view, Bundle savedInstanceState)
Called immediately after onCreateView
has returned, but before any saved state has been restored in to the view. This gives subclasses a chance to initialize themselves once they know their view hierarchy has been completely created. The fragment's view hierarchy is not however attached to its parent at this point.
Parameters | |
---|---|
@NonNull View view |
The View returned by |
Bundle savedInstanceState |
If non-null, this fragment is being re-constructed from a previous saved state as given here. |
setDocumentUri
public final void setDocumentUri(Uri documentUri)
The URI of the PDF document to display defaulting to null
.
When this property is set, the fragment begins loading the PDF document. A visual indicator is displayed while the document is being loaded. Once the loading is fully completed, the onLoadDocumentSuccess
callback is invoked. If an error occurs during the loading phase, the onLoadDocumentError
callback is invoked with the exception.
Accepts the following URI schemes:
- content ([android.content.ContentResolver.SCHEME_CONTENT])
- file ([android.content.ContentResolver.SCHEME_FILE])
Setting a different URI will cancel any ongoing load operation, reset the fragment's state, and display a loading indicator until the new content is loaded.
If the same URI is set multiple times, the load operation will not be restarted. Instead, the existing load operation will continue.
Throws | |
---|---|
kotlin.IllegalArgumentException |
if the uri is not allowed. |
setTextSearchActive
public final void setTextSearchActive(boolean isTextSearchActive)
Controls whether text search mode is active. Defaults to false.
When text search mode is activated, the search menu becomes visible, and search functionality is enabled. Deactivating text search mode hides the search menu, clears search results, and removes any search-related highlights.
Note: This property can only be set after the document has successfully loaded i.e.[onLoadDocumentSuccess] is triggered. Any attempts to change it beforehand will have no effect.
setToolboxVisible
public final void setToolboxVisible(boolean isToolboxVisible)
Indicates whether the toolbox should be visible.
The host app can control this property to show/hide the toolbox based on its state and the onRequestImmersiveMode
callback. The setter updates the UI elements within the fragment accordingly.