Xamarin C# content page not loading image for Android JVM - c#

I have a problem attempting to load an image for the Android JVM in use on Visual Studio 2017 when debugging. Below is a sample of my code:
public class ImageDisplayPage : ContentPage
{
public ImageDisplayPage()
{
Content = new ScrollView
{
Content = new StackLayout()
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children =
{
new Image
{
IsVisible = true,
Aspect = Aspect.AspectFit,
Source = ImageSource.FromResource("Resources.a.png")
}
}
}
};
}
}
I have a folder in my project called "Resources" where the image is supposed to be loaded from, and have followed the path convention used in numerous posts on StackOverFlow and the guide listed here: https://developer.xamarin.com/guides/xamarin-forms/user-interface/images
I use Visual Studio 2017, coding in C# and when I attempt to debug this, the following message is what I get from the debug output:
Image data was invalid: Xamarin.Forms.StreamImageSource
The image in question is an 80kb PNG image.
Thank you in advance for any assistance

You should place your image inside the Resources/drawable folder of your android project and only place the image name and the extension.
public class ImageDisplayPage : ContentPage
{
public ImageDisplayPage()
{
Content = new ScrollView
{
Content = new StackLayout()
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children =
{
new Image
{
IsVisible = true,
Aspect = Aspect.AspectFit,
Source = "a.png"
}
}
}
};
}
}

Related

How to fix "The property Content is set more than once" error in XAML when overriding the ContentProperty of ContentPage

Here is the code I have:
<?xml version="1.0" encoding="UTF-8" ?>
<pages:PopupPage
x:Class="Memorise.DecksTab.CopyDeckPopup"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup">
<Label />
<Label />
</pages:PopupPage>
With backing code:
csharp
[ContentProperty("Contents")]
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CopyDeckPopup : Rg.Plugins.Popup.Pages.PopupPage
{
StackLayout contentStack { get; } = new StackLayout()
{
Spacing = 0,
Padding = new Thickness(0),
Orientation = StackOrientation.Vertical
};
public IList<View> Contents { get => contentStack.Children; }
public CopyDeckPopup(string clickedDeckName, string clickedDeckDescription)
{
BindingContext = new CopyDeckPopupViewModel(clickedDeckName, clickedDeckDescription);
InitializeComponent();
Content = contentStack;
}
In the first XAML I am getting an error on the 2nd Label saying
The property "Content" is set more than once
I can reproduce the behavior.
Nevertheless, on my side even though VS displays that warning/error if i run the project it deploys correctly and both labels are displayed.
It seems that VS does not recognize that the ContentProperty is being overriden, and supposes instead that you are trying to add both Labels to Content, which is wrong since you are adding them to your custom ContentProperty Contents!
Please run the project and let me know if the deploy fails...
UPDATE
The whole issue looks to me like a limitation of VS. At the end it is just a warning, and you should be able to ignore it without any danger.
If on the other hand you opt to set the labels on code you could write
public CopyDeckPopup(string clickedDeckName, string clickedDeckDescription)
{
BindingContext = new CopyDeckPopupViewModel(clickedDeckName, clickedDeckDescription);
InitializeComponent();
Content = contentStack;
Contents.Add(new Label() { Text = "ABC" });
Contents.Add(new Label() { Text = "DEF" });
}
But now this looks redundant since as i understand ContentProperty's is an attribute that the
XAML processor uses to determine the content property.
Decorating types with ContentPropertyAttribute allows shorter XAML syntax.
If you code everything on C# just use the good old Stacklayout and write your code like
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CopyDeckPopup : Rg.Plugins.Popup.Pages.PopupPage
{
public CopyDeckPopup(string clickedDeckName, string clickedDeckDescription)
{
BindingContext = new CopyDeckPopupViewModel(clickedDeckName, clickedDeckDescription);
InitializeComponent();
StackLayout contentStack = new StackLayout()
{
Spacing = 0,
Padding = new Thickness(0),
Orientation = StackOrientation.Vertical,
Children =
{
new Label() { Text = "ABC" },
new Label() { Text = "ABC" }
}
};
Content = contentStack;
}

ZXing.Net generated Barcode doesn't appear in Xamarin Forms

I add ZXing.Net.Mobile, ZXing.Net.Mobile.Forms to project.
Here is the code:
using ZXing.Net.Mobile.Forms;
using ZXing.Net.Mobile;
namespace discountapp
{
public partial class discountappPage : ContentPage
{
ZXingBarcodeImageView barcode;
public void Handle_Clicked(object sender, System.EventArgs e)
{
barcode = new ZXingBarcodeImageView
{
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center
};
barcode.BarcodeFormat = ZXing.BarcodeFormat.EAN_13;
barcode.BarcodeOptions.Height = 25;
barcode.BarcodeOptions.Width = 75;
barcode.BarcodeValue = "2800100028014";
Content = barcode;
}
}
}
For iOS platform also add ZXing.Net.Mobile, ZXing.Net.Mobile.Forms and put some changes in AppDelegate's FinishedLaunching() implementation:
global::ZXing.Net.Mobile.Forms.iOS.Platform.Init();
For Android platform also add ZXing.Net.Mobile, ZXing.Net.Mobile.Forms and put some changes in MainActivity's OnCreate() method:
global::ZXing.Net.Mobile.Forms.Android.Platform.Init();
But after I click the button, it doesn't show Barcode, just nothing without error. Could you help, please!
This issue on the ZXing repo suggests adding
WidthRequest = 410,
HeightRequest = 410,
to ZXingBarcodeImageView which makes the barcode appear although with a bad aspect ratio.

Image from ImageSource

I tried to follow the following example by #CraigDunn with the sample code
someButton.Image = ImageSource.FromFile("imageName.png");
My own try looks like this:
_NavBarPrevPage = new Button
{
Image = ImageSource.FromResource("media_step_back.png")),
BackgroundColor = Color.Red,
TextColor = Color.White,
};
For me, the IDE tells me:
The type Xamarin.Forms.ImageSource can't be converted to Xamarin.Forms.FileImageSource. An explicit conversion exists. Perhaps a conversion is missing.
I think I'm doing exactely what #CraigDunn proposed.
What am I doing wrong?
I've tried the following, and I was able to get rid of the conversion errors in the current answer, but the image is not shown on the button, while it is shown in an image, so the file name is correct:
var nImg = new FileImageSource()
{
File = "media_step_back.png",
};
_NavBarPrevPage = new Button
{
Image =nImg,
};
If the thing you need is a button with image that is implementing by code-behind :
Button button = new Button
{
BackgroundColor = Color.Red,
Font = Font.Default,
FontSize = 10,
TextColor = Color.White,
HeightRequest = 35,
WidthRequest = 80
};
button.Image = "media_step_back.png";
this.Content = button;
Please remember to put the image file (media_step_back.png) in your target platform's resource folder
UPDATE:
You problem were you didn't add the image source in the Property folder and target platform's resource folder (Please note that in below example, I have added a xamarin.png image in each Xamarin "Property" folder, Android's "Resource" and iOS's "Resource" folder)
Below is the updated code that I placed the button into a StackLayout (which also able to works if without StackLayout) :
public class MainPageNew : ContentPage
{
public MainPageNew()
{
StackLayout parent = new StackLayout();
Button button = new Button
{
BackgroundColor = Color.Red,
Font = Font.Default,
FontSize = 10,
TextColor = Color.White,
HeightRequest = 300,
WidthRequest = 80
};
//button.Image = "media_step_back.png";
button.Image = "xamarin.png";
parent.Children.Add(button);
this.Content = parent;
}
Android
iOS:
This is the download link of the updated code.

Convert Xamarin.Forms StackLayout to Android View

I am trying to convert Xamarin.Forms stack layout to Android native View class to use it in IWindowManager.AddView method.
Conversion code is
static class ViewToAndroidViewConverter
{
public static Android.Views.View GetNativeView(this VisualElement view)
{
if (Platform.GetRenderer(view) == null)
Platform.SetRenderer(view, Platform.CreateRenderer(view));
var renderer = Platform.GetRenderer(view);
renderer.Tracker.UpdateLayout();
return renderer.ViewGroup;
}
}
And this is StackLayout that I am trying to convert
StackLayout testView = new StackLayout();
testView.Children.Add(new Label { Text = "Incoming call text" });
testView.Children.Add(new Label { Text = incomingNumber });
testView.BackgroundColor = Color.Green;
windowManager.AddView( testView.GetNativeView(),
new WindowManagerLayoutParams {
Title = "Call title sample",
Gravity = GravityFlags.Center,
Type = WindowManagerTypes.SystemAlert,
Height = 500,
Width = 1080
});
The problem is that this test view is shown, but without label contents (solid green rectangle only).
Is there any way to create an android native view from stack layout with full contents?

How to Remove a Xamarin.Forms TableView and Re-Create It Without Application Crashing

I have a StackLayout in Xamarin.Forms 1.4.2, and from code-behind I am trying to create a table view, and then just for a test I have a button to re-create the TableView in the StackLayout.
If I use the following, that uses a standard TextCell, then I can re-create the TableView as many times as I wish without the application crashing:-
This is on Windows Phone btw:-
TableView tableView1 = new TableView()
{
Intent = TableIntent.Form,
VerticalOptions = LayoutOptions.FillAndExpand
};
myStackLayoutControl.Children.Add(tableView1);
tableView1 = new TableRoot()
{
new TableSection("Section 1")
{
new TextCell()
{
Text = "Text1",
Detail = "Text2"
}
}
};
However when I change the TextCell to a ViewCell such as:-
new ViewCell()
{
View = new Label()
{
Text="hello",
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand
},
Height = 100
}
It will display the TableView correctly on the first execution.
However clicking a button that clears down the TableView and executes the same code to re-create it will run the same code, however straight after it has finished the function it will crash the entire application with an Application_UnhandledException being caught!
The exception caught is:-
MeasureOverride of element 'Xamarin.Forms.Platform.WinPhone.ViewToRendererConverter+WrapperControl' should not return PositiveInfinity or Nan as its DesiredSize.
Does anyone have any ideas how to resolve this?

Categories