I am currently busy with a Xamarin mobile application (only android now) and I am trying to show PDF files. I found a free plugin here: https://github.com/xamarin/docs-archive/tree/master/Recipes/xamarin-forms/Controls/display-pdf but I run into an issue.
When I go to the view I see the PDF controls, but not the PDF itself. (shows a gray screen). Here is a similar issue: display local PDF file in webview control - Displays Blank Pdf File but nothing is working.
I put the PDF file in the correct place with the correct options, see here:
And here you can see the view in the emulator:
I also tried the run the given demo project, but I get a lot of errors :(
Some help would be really appreciated!
CustomView:
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace BizzTimeTest.ViewModels
{
public class CustomPDFWebView : WebView
{
public static readonly BindableProperty UriProperty = BindableProperty.Create(propertyName: "Uri",
returnType: typeof(string),
declaringType: typeof(CustomPDFWebView),
defaultValue: default(string));
public string Uri
{
get { return (string)GetValue(UriProperty); }
set { SetValue(UriProperty, value); }
}
}
}
Custom renderer:
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using BizzTimeTest.Droid;
using BizzTimeTest.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(CustomPDFWebView), typeof(CustomWebViewRenderer))]
namespace BizzTimeTest.Droid
{
[Obsolete]
public class CustomWebViewRenderer : WebViewRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
var customWebView = Element as CustomPDFWebView;
Control.Settings.AllowUniversalAccessFromFileURLs = true;
Control.LoadUrl(string.Format("file:///android_asset/pdfjs/web/viewer.html?file={0}", string.Format("file:///android_asset/Content/{0}", "test_pdf_file.pdf")));
}
}
}
}
xaml
<local:CustomPDFWebView x:Name="custom_pdf_viewer" IsVisible="false"
Uri="test_pdf_file.pdf" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" />
Related
We are using mvvmcross for Xamarin android native but unable to use webview to render html page, please help if anyone tried ...regular xamarin android can do but since we use mvvmcross then that regular won't work
We tried using mvvmcross XAMRIN also added plugin https://nuget.info/packages/MvvmCross.Plugin.WebBrowser/8.0.2 but nothing works
I Did it from View because below LoadDataWithBaseURL() function is not supported/working in ViewModel
i have added below code in View.
WebView.LoadDataWithBaseURL(null, Html, "text/html", "utf-8", null);
In design
<WebView android:id="#+id/ReceiptWebView" android:layout_width="match_parent" android:layout_height="match_parent"/>
It will load HTMl with Table.
This should get you started. I've tested with MvvmCross 8.0.2. This code is slightly modified from Google
You could also probably just use the MvvmCross Web Browser plugin by first saving your HTML to a file then using a "file://..." URI.
using Android.Content;
using Android.Runtime;
using Android.Util;
using Android.Webkit;
using System;
namespace MyApp.Droid.Ui.Controls
{
[Register("myapp.droid.ui.controls.MvxWebView")]
public class MvxWebView : WebView
{
private string _text;
[Preserve(Conditional = true)]
public MvxWebView(Context context, IAttributeSet attrs) : base(context, attrs)
{
}
[Preserve(Conditional = true)]
public string Text
{
get
{
return _text;
}
set
{
if (string.IsNullOrEmpty(value))
{
return;
}
_text = value;
LoadData(_text, "text/html", "utf-8");
UpdatedHtmlContent();
}
}
public event EventHandler HtmlContentChanged;
private void UpdatedHtmlContent()
{
HtmlContentChanged?.Invoke(this, EventArgs.Empty);
}
}
}
Then in your view:
<myapp.droid.ui.controls.MvxWebView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:MvxBind='Text MyHtml' />
...and in your ViewModel:
public string MyHtml
{
get => _myHtml;
set => SetProperty(ref _myHtml, value);
}
MyHtml = "<html><p>Hello, World!</p></html>";
Not necessarily a solution to fix the non-working WebView; but if indeed this is an outstanding compatibility issue, maybe looking into MvvmsCross' WebBrowser plugin might be a suitable workaround fir your application.
I have a contentpage in c# along with a xaml file.
Page1.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace CompanyName.Pages
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Page1 : ContentPage
{
public Page1()
{
InitializeComponent();
}
}
}
Page1.xaml:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="CompanyName.Pages.Page1">
<ContentPage.Content>
<StackLayout>
<Label Text="Welcome to Xamarin.Forms!"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand"
x:Name="test"
/>
<Button Text="Hello, World!" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
This is a fairly large project so to isolate anything that could be causing issues, I set my MainPage to Page1.
App.xaml.cs:
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using System.Threading.Tasks;
using System.Linq;
using CompanyName.DataBases;
using CompanyName.Pages;
using CompanyName.Models;
namespace CompanyName
{
public partial class App : Application
{
public static String OnDatabasesLoaded { get; } = "DatabasesLoaded";
public static Boolean IsDatabasesLoaded { get; private set; }
public App()
{
InitializeComponent();
// The below line is my normal entry point
// MainPage = new NavigationPage(new MainPage()) { BarBackgroundColor = Color.FromHex("#2196f3"),BarTextColor=Color.White};
MainPage = new NavigationPage(new Page1()); // I added this to see if Page1 would even work
}
protected async override void OnStart()
{
// Create the tabels
/*
ColorDatabase colorDatabase = await ColorDatabase.Instance();
QuiltDatabase quiltDatabase = await QuiltDatabase.Instance();
TextDatabase textDatabase = await TextDatabase.Instance();
*/
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
My problem is that my xaml file is not rendered. On both a physical device and the emulator, a blank screen appears (excluding the navigation bar at the top). Both the xaml and code behind are set as Embedded Resources. I am using Visual Studio 2022 with Xamarin.Forms 5.0.0.2478. I made a new project and I was able to create a new page and the layout displayed fine.
I haven't been able to see if this error happens on ios. All my testing has been on Android.
Thanks
"Both the xaml and code behind are set as Embedded Resources."
Why? code and xaml are not resource types. VS has to "compile" those files.
Let VS correctly insert them into your project:
Copy those files someplace safe outside the project.
Delete them from project.
Rt-click on project / Add New Item / Content Page, name "Page1".
Then open your originals in a text editor, so you can copy the text, paste them into the files created by VS.
I would like to open Unity Android application from the setting panel within the custom canvas view.
Can I get a code snippet to bring it within canvas view rather than opening over the whole window?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Runtime.InteropServices;
using System.IO;
using System;
public class GetSetting : MonoBehaviour
{
void Start()
{
#if UNITY_ANDROID
string bundleId = "com.android.settings";
AndroidJavaClass up = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject ca = up.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaObject packageManager = ca.Call<AndroidJavaObject>("getPackageManager");
//if the app is installed, no errors. Else, doesn't get past next line
AndroidJavaObject launchIntent = packageManager.Call<AndroidJavaObject>("getLaunchIntentForPackage", bundleId);
launchIntent.Call<AndroidJavaObject>("addCategory", "android.intent.category.MAIN");
launchIntent.Call<AndroidJavaObject>("addCategory", "android.intent.category.HOME");
launchIntent.Call<AndroidJavaObject>("setFlags", 0x10000000);
ca.Call("startActivity", launchIntent);
up.Dispose();
ca.Dispose();
packageManager.Dispose();
launchIntent.Dispose();
#else
Debug.Log("No Toast setup for this platform.");
#endif
}
}
I have a UserHandler Singleton Class and I declared a variable like this
class UserHandler
{
...
public DatePickerDialog dialog = null;
...
}
Then in my MainActivity.cs file
using Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Support.Design.Widget;
using Android.Support.V7.App;
using Android.Text;
using Android.Views;
using Android.Widget;
using Java.Interop;
using Java.Lang;
using System;
using System.Collections.Generic;
using System.Globalization;
using AlertDialog = Android.Support.V7.App.AlertDialog;
using Exception = System.Exception;
class MainActivity
{
private readonly UserHandler U_Handler = UserHandler.GetInstance;
...
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.activity_main);
...
U_Handler.dialog = new DatePickerDialog(this);
...
}
When I run it on my device (Oppo, Android 8.1.0), it works normally but when I tried it on other device (Samsung, Android 6.0.1), it crashes and upon debugging, it shows this
**Java.Lang.NoSuchMethodError:** 'no non-static method "Landroid/app/DatePickerDialog;.<init>(Landroid/content/Context;)V"'
How to solve this?
Should I use 3rd party Libraries?
Because the constructor DatePickerDialog(Context context) was added in API level 24,when you run it in Samsung, Android 6.0.1,it will throw the Java.Lang.NoSuchMethodError exception.
You can make a judgment call and use the old API when the SDK version is less than 24, and use the new API when it is greater than 24.
The api you could look at DatePickerDialog
I am using Xamarin android
I have Spinner , When I use the setAdapter function I get this error
Error 3 'Android.Widget.Spinner' does not contain a definition for 'setAdepter' and no extension method 'setAdepter' accepting a first argument of type 'Android.Widget.Spinner' could be found (are you missing a using directive or an assembly reference?)
This is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace FSF
{
[Activity(Label = "Request")]
public class RequestHolidayActivity : Activity
{
Spinner spinner_holidayType;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.RequestHoliday);
spinner_holidayType = FindViewById<Spinner>(Resource.Id.RequestHoliday_spinner_holidayT);
var items = new List<string>() { "first", "second", "third", "forth" };
var adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem, items);
spinner_holidayType.setAdepter(adapter);
}
}
}
I tried to solve it , but I didn't find a solution.
There is not SetAdapter method. Instead use the Adapter property and change your code to: spinner_holydayType.Adapter = adapter;