How Can i do this for the Android Xamarin Workbook ?
I'm stack at
Xamarin.Forms.Forms.Init();
var a = new App();
KeyWindow.RootViewController = a.MainPage.CreateViewController();
How to this for Android :
Xamarin.Forms.Forms.Init(needs 2 pram)
KeyWindow.RootViewController
a.MainPage.CreateViewController()
Here Is the Code For iOS
https://developer.xamarin.com/workbooks/xamarin-forms/user-interface/xaml/LoadXaml.workbook
Xamarin.Forms XAML Workbook Demonstration (iOS)
Steps to use XAML
1. Start by importing the NuGets for Xamarin.Forms and the iOS Platform Renderers
```csharp
#r "Xamarin.Forms.Platform.iOS"
#r "Xamarin.Forms.Core"
#r "Xamarin.Forms.Xaml"
#r "Xamarin.Forms.Platform"
```
And for this hack to work, add the Dynamic Xamarin Forms (preview)
NuGet (which contains the magic to load XAML from a string):
```csharp
#r "Xamarin.Forms.Dynamic"
```
2. Add the using statements next:
```csharp
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
```
3. Write up a simple XAML ContentPageto render on iOS:
```csharp
static string xaml = #"<?xml version='1.0' encoding='UTF-8' ?>
<ContentPage xmlns='http://xamarin.com/schemas/2014/forms'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
x:Class='XamlPage'
Title='Xaml Text' Padding='40'>
<StackLayout Orientation='Vertical'>
<Label Text='Hello from XAML' x:Name='helloLabel'/>
<BoxView Color='Blue' WidthRequest='300' HeightRequest='2' />
</StackLayout>
</ContentPage>";
```
4. Bootstrap the Xamarin.Forms app object and and for the main page class, then use the Dynamic Xamarin Forms LoadFromXaml extension method to parse the xaml string:
```csharp
public class App : Application
{
public ContentPage XamlPage {get;set;}
public App ()
{
XamlPage = new ContentPage();
XamlPage.LoadFromXaml (xaml); // loads XAML
MainPage = XamlPage;
}
}
```
5. Finally, set the iOS root view controller directly (in a real Xamarin.Forms app, this would be taken care of by the FormsApplicationDelegate subclass):
```csharp
Xamarin.Forms.Forms.Init();
var a = new App();
KeyWindow.RootViewController = a.MainPage.CreateViewController();
```
One More Thing...
Loading XAML in this way does not allow strongly-typed access to the elements by their x:Name, instead they can only be referenced using FindByNameas shown here to update the label:
```csharp
var l = a.XamlPage.FindByName<Xamarin.Forms.Label>("helloLabel");
l.Text = "Updated by the Workbook!";
a.XamlPage.Content
```
Related
new xamarin programmer here. I need to display a comic image from the internet using a URL but somehow, the system keeps telling me that the link to the url does not work but I don't know why when I instantiate a new UriImageSource.
My first method was to try displaying the image using BitMapImage but it is only available for WindowsForms or WPF so I need an alternative for that as well if UriImageSource does not work for me. I'm on a Mac btw.
This is the xaml:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Weather_App.MainPage">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackLayout Grid.Row="1" Orientation="Horizontal" HorizontalOptions="Center">
<Image x:Name="backgroundImage" Margin="20"/>
</StackLayout>
</Grid>
</ContentPage>
This is the MainPage.cs:
using Xamarin.Forms;
namespace Weather_App
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
private int maxNumber = 0;
private int currentNumber = 0;
public MainPage()
{
InitializeComponent();
ViewModel.ApiHelper.InitializeClient();
string url = Convert.ToString(ComicProcessor.LoadComic());
backgroundImage.Source = new UriImageSource
{
Uri = new Uri(url),
CachingEnabled = false,
CacheValidity = TimeSpan.FromHours(1)
};
}
}
}
Finally, this is the viewmodel/LoadComic method. I tried to return the comic at first instead of the url but since the BitMapImage didn't exist for Mac, I returned the url instead because I thought I could have used it for the UriImageSource instance. The comic properties include an integer Num and a string Img.
namespace Weather_App
{
public class ComicProcessor
{
public static int MaxComicNumber { get; set; }
public async static Task<string> LoadComic(int comicNumber = 0)
{
string url = "";
if (comicNumber > 0)
{
url = $"https://xkcd.com/{comicNumber}/info.0.json";
}
else
{
url = $"https://xkcd.com/info.0.json";
}
using (HttpResponseMessage response = await ViewModel.ApiHelper.ApiClient.GetAsync(url))
{
if (response.IsSuccessStatusCode)//If response successful do something then
{
// Takes data in as json and converted it to the type you have given and match anything that it finds
ComicModel comic = await response.Content.ReadAsAsync<ComicModel>();
if (comicNumber == 0)
{
MaxComicNumber = comic.Num;
}
return url;
}
else
{
// Outputs reason why it wasn't successful
throw new Exception(response.ReasonPhrase);
}
}
}
}
}
I would suggest you use FFImageLoading's CachedImage for this.
It is a library that is vastly accepted by the community and is great with caching and has memory handling options as well.
You can check their Git wiki to understand the library in depth.
Download it form Nuget
Call CachedImageRenderer.Init() on each platform. Let’s put it on MainActivity.cs of our Android project and AppDelegate.cs of iOS.
Then add its namespace and use it like this:
<ffimageloading:CachedImage
HorizontalOptions="Center" VerticalOptions="Center"
DownsampleToViewSize="true"
Source = "{Binding ImageUrl}">
</ffimageloading:CachedImage>
Xamarin.Forms.Image is an option but I personally feel it doesn't work well with URL images.
Also just give CachedImage the URL and it will do the downloading for you!
Goodluck,
Feel free to get back if you have questions.
I'm trying to show a bottom banner on my App but I can't make it show up.
Funny that it was working just fine but after a few weeks without coding it just stopped working and not even test codes from Google show up. Sometimes it works after a compilation and when I unplug the phone and close/open the App again it stop showing the ads again.
I also used the same Admob code into a Unity quiz game I created and over there it works fine everytime.
PS: I'm a bit new to Xamarin and C#, this is my first App.
Here's the relevant code:
MainPage.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"
xmlns:local="clr-namespace:DDP"
x:Class="DDP.MainPage"
BackgroundColor="#3f183d"
Title="My App Title">
<StackLayout BackgroundColor="Transparent" HeightRequest="70" HorizontalOptions="Start" VerticalOptions="Center" WidthRequest="1000">
<local:AdMobView x:Name="adMobView" HorizontalOptions="FillAndExpand" VerticalOptions="EndAndExpand"/>
</StackLayout>
</ContentPage>
MainPage.xaml.cs
public MainPage()
{
InitializeComponent();
BindingContext = this;
adMobView.AdUnitId = AdMobView.codigoAdmob;
}
AdMobView.cs
using Xamarin.Forms;
namespace DDP
{
public class AdMobView : View
{
public static readonly BindableProperty AdUnitIdProperty = BindableProperty.Create(
nameof(AdUnitId),
typeof(string),
typeof(AdMobView),
string.Empty);
public string AdUnitId
{
get => (string)GetValue(AdUnitIdProperty);
set => SetValue(AdUnitIdProperty, value);
}
//admob google test code
public static string codigoAdmob = "ca-app-pub-xxxxx/xxxxx";
}
}
AdMobViewRenderer.cs
using System.ComponentModel;
using DDP;
using DDP.Droid;
using Android.Content;
using Android.Gms.Ads;
using Android.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(AdMobView), typeof(AdMobViewRenderer))]
namespace DDP.Droid
{
public class AdMobViewRenderer : ViewRenderer<AdMobView, AdView>
{
public AdMobViewRenderer(Context context) : base(context) { }
protected override void OnElementChanged(ElementChangedEventArgs<AdMobView> e)
{
base.OnElementChanged(e);
if (e.NewElement != null && Control == null)
{
SetNativeControl(CreateAdView());
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == nameof(AdView.AdUnitId))
Control.AdUnitId = Element.AdUnitId;
}
private AdView CreateAdView()
{
var adView = new AdView(Context)
{
AdSize = AdSize.SmartBanner,
AdUnitId = Element.AdUnitId
};
adView.LayoutParameters = new LinearLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent);
adView.LoadAd(new AdRequest.Builder().Build());
return adView;
}
}
}
MainActivity.cs
//somecode
base.OnCreate(bundle);
MobileAds.Initialize(ApplicationContext, "ca-app-pub-xxxxx/xxxxx");
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
//somecode
AndroidManifest.xml
Other info
I'm using 'Xamarin.GooglePlayServices.Ads.Lite' NuGet package and I checked permissions to 'Network_State' and 'Internet'
Thanks !
Update 1: Catlog log:
--------- beginning of crash
--------- beginning of system
--------- beginning of main
11-19 11:31:04.852 11568 11568 I Ads : Updating ad debug logging enablement.
11-19 11:31:06.407 11568 11596 W Ads : Update ad debug logging enablement as false
11-19 11:31:07.109 11568 11568 I Ads : Use AdRequest.Builder.addTestDevice("1BE57C53121A02D9EF3DD79A87C60D3C") to get test ads on this device.
11-19 11:31:07.916 11568 11593 W Ads : Not retrying to fetch app settings
11-19 11:31:08.118 27571 11755 I Ads : SDK version: afma-sdk-a-v14574021.11400000.1
11-19 11:31:08.901 11568 11568 I Ads : Ad failed to load : 3
Filter by the TAG of Ads and you will see different Information and/or Warning log entries concerning AdMob. These will range from timed outs and load failures (usually related to no Internet access) to not refreshing the ad since it is not currently visible in the UI (but an AdView instance was created), etc...
Example:
adb logcat -s Ads
Example Output (Not a complete list):
I Ads : Starting ad request.
I Ads : SDK version: XXXXXXXXXX
I Ads : This request is sent from a test device.
I Ads : Scheduling ad refresh 70000 milliseconds from now.
I Ads : Ad is not visible. Not refreshing ad.
W Ads : There was a problem getting an ad response. ErrorCode: 0
W Ads : Failed to load ad: 0
W Ads : Not retrying to fetch app settings
W Ads : Invoke Firebase method getInstance error.
W Ads : The Google Mobile Ads SDK will not integrate with Firebase. Admob/Firebase integration requires the latest Firebase SDK jar, but Firebase SDK is either missing or out of date
W Ads : App does not have the required permissions to get location
W Ads : Timed out waiting for ad response.
W Ads : Failed to load ad: 2
I'm sorry that can't say how to fix this but I think it is related to Chrome version, chrome ships webview which admob is using. I had a perfectly working admob ads in my xamarin forms app on Nexus 5X device with Chrome 60 but upgrading to Chrome 70+ broke all ads.
I will be glad to any help.
How correctly to specify a way to an xml a file?
My application is crashing out of this code.
XDocument xDoc = XDocument.Load("XMLBase/Data.xml");
Sorry gyus. I will try to correct myself.
When testing the application through XamarinLive no problems.
After the application is archived and signed. I install the application (file .apk) on the phone.
I launch the application on the phone.
I turn to pages with a problem code and the application crashes.
Full page code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using System.Xml.Linq;
using Xamarin.Forms.Xaml;
namespace App14
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ListMain : ContentPage
{
public List<string> Students;
public ListMain ()
{
InitializeComponent ();
Students = new List<string>();
XDocument xDoc = XDocument.Load("XMLBase/Data.xml");
foreach (XElement xe in xDoc.Element("students").Elements("mainStudent"))
{
Students.Add(xe.Element("student").Value);
}
foreach (string student in Students)
{
stackLayout.Children.Add(new Label { Text = student, FontSize = 20, HorizontalOptions = LayoutOptions.StartAndExpand });
stackLayout.Children.Add(new Label { Text = "DEL", FontSize = 20, HorizontalOptions = LayoutOptions.End });
}
}
}
}
This code fragment below can be used as a debug/learning aid to see all the manifest resource names in your assembly. Then, use the names shown as needed in your assembly for your resources.
var assembly = Assembly.GetExecutingAssembly();
foreach (var resourceName in assembly.GetManifestResourceNames())
System.Console.WriteLine(resourceName);
Screen shot #1 shows an example of the resource names produced by the code fragment above in my particular assembly. The one in red is used in the code fragment below. The code fragment below is an example of how I read the resource into a string variable (a .txt file in my case)
Screen shot #2 shows the resources's properties. The resource needs to be an Embedded Resource for the code to work
string excludedTablesString = new StreamReader((Assembly.GetExecutingAssembly()).GetManifestResourceStream("DataReviewUtility.Resources.ExcludedTables.txt")).ReadToEnd();
Screen Shot #1
Screen Shot #2
I am trying to load a local HTML page in a webview with Xamarin forms.
I am using the basic example in the dev docs although I can get a URL to load I can't get my own HTML pages to load. This only needs to be done through Android so there is no worries about about IOS and Windows.
The Xaml:
<WebView
x:Name="webviewjava"></WebView>
The code behind:
public partial class javscriptExample : ContentPage
{
public interface IBaseUrl { string Get(); }
public javscriptExample()
{
InitializeComponent();
var source = new HtmlWebViewSource();
source.BaseUrl = DependencyService.Get<IBaseUrl>().Get();
webviewjava.Source = source;
}
}
The platform specific file (LocalFile.cs):
Just to note this has been set as an Android asset.
[assembly: Dependency(typeof(LocalFiles))]
namespace maptesting.Droid
{
public class LocalFiles: IBaseUrl
{
public string Get()
{
return "file:///android_asset/";
}
}
}
and under the asset's folder there is a 'TestWebPage.html', also set as an Android asset.
Although I dont know what the problem is I have put it through debug and the base url is coming back blank. Just to be clear im not getting a file not found, the screen is simply blank.
Also, and Im not sure if this makes a difference. There is no syntax highlighting on 'IBaseUrl' in the LocalFiles.cs file. So I'm not sure if it can 'see' it.
Any ideas?
I am also suffering with the same issue,but I resolved in the following way
Use "UrlWebViewSource" instead of "HtmlWebViewSource"
var urlSource = new UrlWebViewSource();
string baseUrl = DependencyService.Get<IWebViewBaseUrl>().GetBaseUrl();
string filePathUrl = Path.Combine(baseUrl, "imprint.html");
urlSource.Url = filePathUrl;
WebBrowser.Source = urlSource;
You must check the file properties for Build Action = BundleResource
Try this code to load local html file
var source = new HtmlWebViewSource();
string url = DependencyService.Get<IBaseUrl>().GetBaseUrl();
string TempUrl = Path.Combine(url, "terms.html");
source.BaseUrl = url;
string html;
try
{
using (var sr = new StreamReader(TempUrl))
{
html = sr.ReadToEnd();
source.Html = html;
}
}
catch(Exception ex){
Console.WriteLine(ex.Message);
}
Implementations of the interface for each platform must then be provided
iOS
[assembly: Dependency(typeof(BaseUrl))]
namespace yournamespace
{
public class BaseUrl: IBaseUrl
{
public string GetBaseUrl()
{
return NSBundle.MainBundle.BundlePath;
}
}
}
Android
[assembly: Dependency (typeof(BaseUrl))]
namespace yournamespace {
public class BaseUrl_Android : IBaseUrl {
public string Get() {
return "file:///android_asset/";
}
}
}
WebView.BaseUrl only tells the WebView where to start looking for files. It's the root folder of the "web site". By default browsers will load the file index.html, so if you rename your file to index.html I believe it should load automatically.
I think this should be possible too:
webviewjava.BaseUrl = DependencyService.Get<IBaseUrl>().Get();
webviewjava.Source = "TestWebPage.html";
Here you're saying "use this location as the default place to look for files" and "look up this file and use it as the source for the HTML".
This is an old post but It may help someone looking to implement with Android, iOS and UWP with just one HTML file. With this approach you only use one HTML file for all platforms.
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/files?tabs=vsmac#loading-files-embedded-as-resources
Im not sure if this counts but I found a work around. Instead of taking the above route I simply did this:
webviewjava.Source = "file:///android_asset/TestWebPage.html";
in the code behind, and just left out the IBaseUrl call altogether.
This works as its supposed to.
I am building an application that uses the Xamarin.Forms WebView. Everything works fine on Android, iOS and UWP. But sometimes there is an image in the HtmlSource of the WebView that doesn't load. I can't find out what the problem is.
I'm trying to show this html in the WebView:
<p><img src="https://www.loi.nl/~/media/images/logos/vakgebieden/ipma.jpg" alt="Img did not load" /></p>
This code works fine on UWP and shows the correct image. But when running the exact same code on Android or iOS, the image doesn't show up.
I can't find out why the WebView doesn't load this image on Android or iOS.
These images DID load succesful on every platform: https://www.rabobank.nl/static/generic/css/images/s14/rabobank-logo.png
http://www.learnit.nl/static/nl/gratiscursus/photoshop/8/ph_07.jpg
https://www.volkswagen.nl/~/media/Volkswagen/Images/Modellen/nieuwe%20up/up-hero-menu2.ashx?bc=White&as=0&h=310&w=860
http://www.volkswagen.nl/~/media/Volkswagen/Images/Modellen/nieuwe%20up/up-hero-menu2.ashx?bc=White&as=0&h=310&w=860
The code I use to show the WebView:
var browser = new WebView();
var htmlSource = new HtmlWebViewSource();
htmlSource.Html = #"<html><head> <link rel=""stylesheet"" href=""adefault.css""> </head><body>" + c.HtmlSource + "</body></html>";
browser.Source = htmlSource;
htmlSource.BaseUrl = DependencyService.Get<IBaseURL>().Get();
browser.VerticalOptions = LayoutOptions.FillAndExpand;
browser.HorizontalOptions = LayoutOptions.FillAndExpand;
browser.WidthRequest = 100;
browser.HeightRequest = 1000;
The c.HtmlSource in this case is the code containing the <p> showed at this start of the question.
Can somebody tell me why this specific image is not loading in the Xamarin.Forms WebView on the Android and iOS platform?
The code of the class that implements IBaseURL on iOS:
[assembly: Dependency (typeof (BaseUrl_iOS))]
namespace LOI.iOS
{
public class BaseUrl_iOS : IBaseURL
{
public string Get()
{
return NSBundle.MainBundle.BundlePath;
}
}
}
The code of the class that implements IBaseURL on Android:
[assembly: Dependency (typeof (BaseUrl_Android))]
namespace LOI.Droid
{
public class BaseUrl_Android : IBaseURL
{
public string Get()
{
return "file:///android_asset/";
}
}
}
The IBaseURL interface:
public interface IBaseURL
{
string Get();
}