> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/xamarin/guides/getting-started/using-fragment.md).

# Display document in fragment in Xamarin

Learn how to integrate a PDF viewer into your Xamarin.Android app with PdfViewCtrlTabHostFragment2. Follow step-by-step instructions for setting up permissions, launching the viewer, and customizing f

{% hint style="info" %}
**This tutorial only applies to Xamarin.Android.**
{% endhint %}

All actions related to the PDF viewer are handled through the [`PdfViewCtrlTabHostFragment2`](https://sdk.apryse.com/api/xamarinandroid/tools/api/pdftron.PDF.Controls.PdfViewCtrlTabHostFragment2.html). This fragment extends [`androidx.fragment.app.Fragment`](https://developer.android.com/reference/kotlin/androidx/fragment/app/Fragment.html) and is responsible for showing documents in tabs.

![](https://653871032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FgjsBtuYmcKhWOdM9VCg4%2Fuploads%2Fgit-blob-ffa3eaa183402c0184a8845cef4ef7492205fd4b%2F1ed8a2fb5f4d6204964ec7788bb1094df6d78c7e-600x1200.gif?alt=media)

## Prerequisites

* [Integrated Apryse into your project](/xamarin/get-started/get-started.md) and added the `PDFTron.Android.Tools` NuGet package into your project.
* Minimum API: 21 (using AndroidX)
* Compile API: 35
* Recommended target API: 35

{% hint style="info" %}
**No trial license key required.**

The trial of Apryse Mobile SDK does not require a trial key. A commercial license key is required for use in a production environment. Please [contact sales](https://apryse.com/form/contact-sales) to purchase a commercial key or if you need any other license key assistance.
{% endhint %}

{% hint style="warning" %}
**Keep your license keys confidential.**

License keys are uniquely generated. Please make sure that it is not publicly available (e.g. in your public GitHub).
{% endhint %}

## Step 1: Update AndroidManifest.xml

1. In order to support all the features in `PdfViewCtrlTabHostFragment2`, we will need to add the Android permissions listed in [this table](/xamarin/learn-more/permissions.md#android-permissions-list). However if you would like to disable certain features and customize your document viewer, you should leave out unnecessary permissions.

{% hint style="warning" %}
**Storage permission**

Please note that from Android 6.0 (API 23) and up, applications need to request storage permission at runtime before accessing any files on device.
{% endhint %}

1. Enable `largeHeap` and `usesClearTextTraffic`:

{% tabs %}
{% tab title="XML" %}
{% code lineNumbers="true" %}

```xml
<application ... android:largeHeap="true" android:usesCleartextTraffic="true">
</application>
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="warning" %}
**If your app is targeting Android SDK version 28 or higher, you will need to add the android:usesCleartextTraffic="true" attribute in your application tag to open HTTP files in the viewer. If you are only working with HTTPS files, this is not required.**
{% endhint %}

1. Define your Activity to extend `AppCompatActivity` and use an AppCompat theme:

{% tabs %}
{% tab title="C#" %}
{% code lineNumbers="true" %}

```csharp
[Activity(Label = "MyReaderActivity", ConfigurationChanges = Android.Content.PM.ConfigChanges.ScreenSize | Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.KeyboardHidden, Theme = "@style/PDFTronAppTheme", WindowSoftInputMode = SoftInput.AdjustPan)]
public class MyReaderActivity : AppCompatActivity
{
  ...
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

1. If you have not done so already, add your license in the `AndroidManifest.xml` file. The final `AndroidManifest.xml` file should look something like this:

{% tabs %}
{% tab title="XML" %}
{% code lineNumbers="true" %}

```xml
<manifest ...>
    <!-- Required permissions are added here -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO" />

    <!-- Add enable largeHeap and usesCleartextTraffic -->
    <application ... android:largeHeap="true" android:usesCleartextTraffic="true">    

        <!-- Add license key in meta-data tag here. This should be inside the application tag. -->
        <meta-data android:name="pdftron_license_key" android:value="your_license_key_goes_here"/>

    </application>
</manifest>
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Step 2: Launch the viewer

Use `ViewerBuilder2` to create an instance of `PdfViewCtrlTabHostFragment2`, and add it to your activity layout. To add a document viewer fragment for a given password-protected file, call the following method in your activity:

{% tabs %}
{% tab title="C#" %}
{% code lineNumbers="true" %}

```csharp
// Add a viewer fragment to the layout container in the specified activity, 
// and returns the added fragment
public PdfViewCtrlTabHostFragment2 addViewerFragment(int fragmentContainer, 
    AppCompatActivity activity, Uri fileUri, String password)
{
    // Create the viewer fragment
    PdfViewCtrlTabHostFragment2 fragment = 
        (PdfViewCtrlTabHostFragment2) ViewerBuilder2.WithUri(fileUri, password).Build(this);

    // Add the fragment to the layout fragment container
    activity.SupportFragmentManager.BeginTransaction()
        .Replace(fragmentContainer, fragment, null)
        .Commit();

    return fragment;
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

where `fragmentContainer` is the resource id of a layout in your activity that will contain your fragment:

**For example:**

{% tabs %}
{% tab title="XML" %}
{% code lineNumbers="true" %}

```xml
<?xml version="1.0" encoding="utf-8"?>
<!-- This FrameLayout will contain our viewer fragment-->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent"/>
```

{% endcode %}
{% endtab %}
{% endtabs %}

Alternatively if you have extended [`PdfViewCtrlTabFragment2`](https://sdk.apryse.com/api/xamarinandroid/tools/api/pdftron.PDF.Controls.PdfViewCtrlTabFragment2.html) or `PdfViewCtrlTabHostFragment2`, you can specify your custom classes using the `ViewerBuilder2.usingTabClass()` method and the `ViewerBuilder2.build()` method as follows:

{% tabs %}
{% tab title="C#" %}
{% code lineNumbers="true" %}

```csharp
// Add a viewer fragment to the layout container in the specified activity, 
// and returns the added fragment
public MyCustomTabHostFragment addViewerFragment(int fragmentContainer, 
    AppCompatActivity activity, Uri fileUri, String password)
{
    // Create the viewer fragment with a custom 
    // PdfViewCtrlTabFragment2 and PdfViewCtrlTabHostFragment2
    PdfViewCtrlTabHostFragment2 fragment = 
        (PdfViewCtrlTabHostFragment2) ViewerBuilder2.WithUri(fileUri, password)
                    .UsingTabClass(Java.Lang.Class.FromType(typeof(MyCustomTabFragment)))
                    .Build(activity, Java.Lang.Class.FromType(typeof(MyCustomTabHostFragment)));

    // Add the fragment to the layout fragment container
    activity.SupportFragmentManager.BeginTransaction()
        .Replace(fragmentContainer, fragment, null)
        .Commit();
        
    return fragment;
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}
Since Apryse uses the Fragment class from the Support Library, your activity must extend [`AppCompatActivity`](https://developer.android.com/reference/androidx/appcompat/app/AppCompatActivity/)and call [`getSupportFragmentManager()`](https://developer.android.com/reference/androidx/fragment/app/FragmentActivity.html#getSupportFragmentManager\(\)) to get the [`FragmentManager`](https://developer.android.com/reference/androidx/fragment/app/FragmentManager.html).
{% endhint %}

## Step 3: Customize the viewer

### Customize document viewer style

* If you would like to customize the appearance of the viewer activity, define `PDFTronAppTheme` in `styles.xml`:You can learn more about this in the [customize the viewer's theme guide ](/xamarin/guides/viewer-components/custom-theme-a.md).

{% tabs %}
{% tab title="XML" %}
{% code lineNumbers="true" %}

```xml
<style name="PDFTronAppTheme" parent="PDFTronAppThemeBase"> <item name="colorPrimary">@color/app_color_primary_day</item> <item name="colorPrimaryDark">@color/app_color_primary_dark_day</item> <item name="colorAccent">@color/app_color_accent</item> <!-- Action bar --> <item name="actionModeBackground">?attr/colorPrimary</item> <item name="windowActionModeOverlay">true</item> </style>
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}
`PdfViewCtrlTabHostFragment2` uses the `AppCompat` theme for material colors. Make sure that the value of `android:theme` in your `activity` tag also extends the `AppCompat` theme.
{% endhint %}

### Customize using ViewerConfig

* If you would like to customize certain viewer settings or the UI of `PdfViewCtrlTabHostFragment2`, you can use [`ViewerConfig.Builder`](https://sdk.apryse.com/api/xamarinandroid/tools/api/pdftron.PDF.Config.ViewerConfig.Builder.html). For example:

{% tabs %}
{% tab title="C#" %}
{% code lineNumbers="true" %}

```csharp
public PdfViewCtrlTabHostFragment2 createUsingViewerConfig(Context context, Uri fileUri, String password)
  {
      // Create a ViewerConfig object with custom settings
      var config = new ViewerConfig.Builder()
          .FullscreenModeEnabled(true)
          .MultiTabEnabled(true)
          .DocumentEditingEnabled(true)
          .LongPressQuickMenuEnabled(true)
          .ToolbarTitle("Host Fragment")
          .ShowSearchView(true)
          .Build();

      // Pass in the ViewerConfig object into the ViewerBuilder2
      return (PdfViewCtrlTabHostFragment2) ViewerBuilder2.WithUri(fileUri, password)
          .UsingConfig(config).Build(context);
  }
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}
For details on customizing the UI and using `ViewerConfig.Builder`, check out the [configuration tutorial ](/xamarin/basic-operations/basics/fragment-config.md).
{% endhint %}

### Customize the options toolbar

![](https://653871032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FgjsBtuYmcKhWOdM9VCg4%2Fuploads%2Fgit-blob-e41c35c02fc53c34c2bf69c4166af168c6a60fb9%2Fd44a9a43437d8c0ca7cf7134f08651f73852f248-423x58.jpg?alt=media)

The default toolbar menu consists of the following buttons on phones:

* App navigation
* Toolbar switcher
* Tab switcher
* Overflow menu

![](https://653871032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FgjsBtuYmcKhWOdM9VCg4%2Fuploads%2Fgit-blob-a321ec29780e9218dae808e1f8ebb95c6e3d7858%2Fd06f2cc6f6ab14ecc3d8b698d354f6ea6a625fb1-643x44.jpg?alt=media)

The default toolbar menu consists of the following buttons on tablets:

* App navigation
* Toolbar switcher
* Document text search
* View mode configuration
* Thumbnails browser
* List container
* Overflow menu

You can fully customize the toolbar menu and the navigation icon by calling the following in `ViewerBuilder2`, with custom menu resource and drawable resource files:

{% tabs %}
{% tab title="C#" %}
{% code lineNumbers="true" %}

```csharp
public PdfViewCtrlTabHostFragment2 createUsingCustomToolbar(Context context, Uri fileUri, int navIcon, int[] menuRes)
{
    return ViewerBuilder2.WithUri(fileUri)
            .UsingCustomToolbar(menuRes)// Specify a custom toolbar
            .UsingNavIcon(navIcon)      // Specify a custom navigation component
            .Build(context);
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

To change the icon color and overflow icon color, in `styles.xml`:

{% tabs %}
{% tab title="XML" %}
{% code lineNumbers="true" %}

```xml
<style name="ToolbarTheme" parent="ThemeOverlay.AppCompat.Dark.ActionBar"> <item name="colorControlNormal">@color/red</item> <item name="iconTint">@color/red</item> </style>
```

{% endcode %}
{% endtab %}
{% endtabs %}

To change the navigation icon color, in `styles.xml` (assume `MyTheme` is used as the app theme):

{% tabs %}
{% tab title="C#" %}
{% code lineNumbers="true" %}

```csharp
<style name="MyTheme" parent="PDFTronAppTheme"> <item name="toolbarNavigationButtonStyle">@style/ToolbarButtonNavigationStyle</item> </style>

<style name="ToolbarButtonNavigationStyle" parent="Widget.AppCompat.Toolbar.Button.Navigation"> <item name="android:tint">@color/red</item> </style>
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}

## Step 4: Interact with the fragment

{% endhint %}

If you would like to interact with the host fragment you can override the methods that you are interested in through events. For example, you may want to override [`ToolbarOptionsItemSelected`](https://sdk.apryse.com/api/xamarinandroid/tools/api/pdftron.PDF.Controls.PdfViewCtrlTabHostFragment2.html#pdftron_PDF_Controls_PdfViewCtrlTabHostFragment_ToolbarOptionsItemSelected) when you add a new menu item, so when the item is clicked you can get a callback. As another example, you can get the callback when the navigation icon is clicked if you override [`NavButtonPressed`](https://sdk.apryse.com/api/xamarinandroid/tools/api/pdftron.PDF.Controls.PdfViewCtrlTabHostFragment2.html#pdftron_PDF_Controls_PdfViewCtrlTabHostFragment_NavButtonPressed).

Here's an example that replaces the default navigation icon and uses a custom toolbar:

{% tabs %}
{% tab title="C#" %}
{% code lineNumbers="true" %}

```csharp
var PdfViewCtrlTabHostFragment2 =
    (PdfViewCtrlTabHostFragment2) ViewerBuilder2.WithUri(fileUri)
        // Specify a custom toolbar
        .UsingCustomToolbar(new int[] { Resource.Menu.my_custom_toolbar })
        // Specify a custom navigation component
        .UsingNavIcon(Resource.Drawable.ic_arrow_back_white_24dp)      
        .Build(context);

PdfViewCtrlTabHostFragment2.ToolbarOptionsItemSelected += (sender, e) =>
{
    // Called when toolbar option item is selected
};

PdfViewCtrlTabHostFragment2.NavButtonPressed += (sender, e) =>
{
    // Called when navigation button has been clicked
};
```

{% endcode %}
{% endtab %}
{% endtabs %}

where `ic_arrow_back_white_24dp.xml` is a drawable resource file for a back arrow icon, and `my_custom_toolbar.xml` is a menu resource file that contains:

{% tabs %}
{% tab title="XML" %}
{% code lineNumbers="true" %}

```xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
     <item android:id="@+id/action_settings" android:icon="@drawable/ic_settings" android:title="@string/action_settings" app:showAsAction="ifRoom"/>
    <item android:id="@+id/action_show_toast" android:title="Show toast" app:showAsAction="never" />
</menu>
```

{% endcode %}
{% endtab %}
{% endtabs %}

This sample replaces the navigation icon, removes all toolbar buttons except the annotation toolbar button, and adds a new `Show Toast` button:

![](https://653871032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FgjsBtuYmcKhWOdM9VCg4%2Fuploads%2Fgit-blob-93ca039c7f05b7bf6d2e1002faafe358b11256d4%2F2bf0bfd4720aa2ad30e5539cce26f5ce425dd7df-422x816.gif?alt=media)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/xamarin/guides/getting-started/using-fragment.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
