Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all 77050 articles
Browse latest View live

Render the control with their appropriate native images in Xamarin Forms

$
0
0

XamarinForms has a lot of issues when it comes to renderers. I mean, it works for the XamarinForms controls because the rendering process is very tightly coupled. Like for instance, Why would ever the Xamarin.Forms.Grid translates to Windows.UI.XamlFrameworkElement instead of Windows.UI.Xaml.Controls.Grid. In the end this is why we uses XamarinForms. You write an agnostic code and it translates to it's very native images across all platforms. Not with a highly manipulating manner. I'm taking UWP as an example but if we spread this across all platforms, We will find that the Grid Translates to View in Android and UIView in iOS. You simply take the agnostic types for representing a control on each platform and start stuffing it with a lot of properties that are NOT native.
For instance, In the grid renderer in UWP. Why would ever the background represented by a canvas behind the content of the grid. Why wouldn't be presented by a brush which IS a member of the Windows.UI.Xaml.Controls.Grid. A lot of people use XamarinForms for the back-end sharing. And also a lot of people use XamarinForms for the UI sharing. And i use Xamarin Forms for both.

I started noticing the problem when i was creating an effect for applying an AcrylicBrush

This is an open discussion for what could be done in order to improve this


Has anyone seen example of AR Kit/Targeted images or AR Core/Augmented Images on Xam Forms or Native

$
0
0

Hello,

I'm looking to build a mobile application that uses AR to target a poster on the wall and overlay an AR object. Has anyone seen the targeted images/augmented images functionality used in a Xamarin application?

From the examples I've found, they only implement the basic AR object on screen. Any help would be appreciated!

How to use OnPropertyElementChanges in Effects

$
0
0

How to use OnPropertyElementChanges on effects to track changes so that i update it. The trick is the properties i need to update is in the effect itself.
So i have an effect with two properties and both of them implements INotifyPropertyChanges. A provided sample would be very helpful

Custom property of a custom control not being set

$
0
0

I'm trying to create a custom entry control with EntryType property which I then use inside custom renderers to set platform specific values. But the EntryType is never set when used from Xaml. Here's my code:


    public class ExtendedEntry : Xamarin.Forms.Entry
    {

        public static readonly BindableProperty EntryTypeProperty = BindableProperty.Create(
            propertyName: "EntryType",
            returnType: typeof(int),
            declaringType: typeof(EntryTextType),
            defaultValue: 1
            );

        public EntryTextType EntryType
        {
            get
            {
                return (EntryTextType)GetValue(EntryTypeProperty);
            }
            set
            {
                SetValue(EntryTypeProperty, value);

            }
        }

        protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            base.OnPropertyChanged(propertyName);

            if (propertyName == EntryTypeProperty.PropertyName)
            {

            }
        }
    }

    public enum EntryTextType
    {
        Any,
        Numeric,
        Url,
        Email
    }

    public class ExtendedEntryRenderer : EntryRenderer
    {
        public ExtendedEntryRenderer(Android.Content.Context context) : base(context)
        {

        }

        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged(e);

            if (Control != null)
            {
                var element = (ExtendedEntry)Element;
                Control.Hint = element.Placeholder;
                switch(element.EntryType)
                {
                    case EntryTextType.Numeric:
                        Control.SetRawInputType(Android.Text.InputTypes.ClassNumber);
                        break;
                    default:
                        break;
                }
            }
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            var p = e.PropertyName;
            base.OnElementPropertyChanged(sender, e);
        }

    }

And then in XAML, I use the control as this:

         <controls:ExtendedEntry Placeholder="Password" IsPassword="True" Text="{Binding Secret}" EntryType="Any"/>

The problem is, EntryType never gets set to EntryTextType.Any, and always uses the default value of EntryTextType.Numeric. What am I missing here? Thanks.

Return to same page when app is back into foreground.

$
0
0

Hi,

The main page of my app is subscribed to receiving push notifications. When the app is in the foreground, the notification data is displayed on the page(when notification comes in).

When the app is in the background I want that when the user clicks the notification, the page with the push notification information is loaded.

If the page is in the background, is it still subscribed to receiving notifications and thus still receives notifications? Or clicking the notification in the notification tray just load a new page, re-subscribes and has missed the previous notification information?

How can I achieve this? Thank you in advance.

The order of the code into my project

$
0
0

My goal is to connect to WiFi network with known SSID and password using Xamarin.Forms. I can't understand the order of the code and its situation into project. Can anyone help me with this problem. If it won't be hard for you could you write a simple example project that's function will be the connection to the known WiFi. It will really help me. Cause I fight with this about 3 weeks :(

How/where best to wire and unwire event handlers in custom renderers?

$
0
0

For my ContentPages, I wire up event handlers in OnAppearing and unwire them in OnDisappearing.

I am just browsing through the various custom renderers that I have (initially for iOS, will check others shortly). They wire up event handlers in OnElementChanged, but some do the unwiring in OnElementChanged (if OldElement != null and Control != null) and some do it in Dispose.

What is considered best practice (I prefer symmetrical stuff like OnAppearing and OnDisappearing, so it may be using OnElementChanged for both is the closest to symmetrical, but are there better options?

Xamarin Forms MVVM parent / child example?

$
0
0

Is there a parent / child example out there somewhere? I’ve not seen one out there.

To be clear, I am not referring to a MasterDetailPage.

I am using Visual Studio 2017 Mac with a netstandard2.0 Xamarin Forms iOS / Android project solution. I’ve added sqlite-net-pcl version 1.4.118 NuGet; using XF version 3.1.0.x. I tried using the sqlite-net Extensions, but that crashes when I try to use OneToMany / ManyToOne.

Two models: a Player and Team (see below).

There can be many Players. A team can have 1 to many Players on it.

There are plenty of examples how to deal with the MVVM child (Player), so no examples need for that. I wanted a ContentPage that would allow the user to enter a new Team (name) at the top and a ListView / Grid of Players for that team via a Switch or Checkbox listed below the team name.

Models:
namespace Project.Models
 {

[Table(“Player”)]

public class Player

{

[PrimaryKey, AutoIncrement]

public int Id { get; set; }
public string Name { get; set; }

public string Position { get; set; }

}

}

namespace Project.Models
 {

 [Table(“Team”)]

public class Team

{

 [PrimaryKey, AutoIncrement]

public int Id { get; set; }

 public string Name { get; set; }

 public List Players { get; set; }

}

}

Note: the List Players will generate a runtime error. Note: I did think of a way to stuff the int list into a string and get it back out as a int list; however, I thought it important to get the concept across rather than it correctly working but a muddled.

That said, I’d think that this should be a (relatively speaking) common design pattern and I’d like to see an MVVM example of how to do this. I’ve searched the forum, but didn’t see any non-native XF example. I’ve also done a Bing search and didn’t find it an example there either.

Can anyone point me to some good links?


Errors uploading APK in Android Things Console

$
0
0

Hi,

I've built a release version of a Xamarin.Forms app for Android Things that runs on the Raspberry Pi 3 both in debug and in release. I'm trying to upload the apk to Android Things Console and I keep getting an error that "All shared object libraries(*.so) in the APK should be uncompressed.". Has anyone run into this and solved it?

I've tried building with a binding using the preview 8 and also tried using the package for preview 7 just in case it was something to do with the binding dll being compressed.

Steve

Exception When Removing Button from StackLayout on Android

$
0
0

Hi there,
I have a cross platform iOS/Android Forms project that crashes on Android any time a Button is removed from a StackLayout, or a StackLayout with a Button in it is removed from the page's Content.

The most simple version of the code in Forms that causes the crash looks like this:
`
public class LoginPageTest : ContentPage
{
StackLayout Layout1;
StackLayout Layout2;
Button OnBoardLoginButton;
Label Label1;

public LoginPageTest()
{
    Layout1 = new StackLayout { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand };

    OnBoardLoginButton = new Button { Text = "PRESS ME" };
    OnBoardLoginButton.Pressed += OnLoginButtonPressed;
    Layout1.Children.Add(OnBoardLoginButton);

    Content = Layout1;
}

private void OnLoginButtonPressed(object sender, EventArgs e)
{
    Layout1.Children.Remove(OnBoardLoginButton);
}

}
`

The error reported is:
Unable to activate instance of type Xamarin.Forms.Platform.Android.AppCompat.ButtonRenderer from native handle 0xbe8b2e6c (key_handle 0x3004107).

The same error happens on Android (but not iOS) if the Content property of the page is changed from one StackLayout with a Button in it to another StackLayout.

This error doesn't happen on iOS. It only happens on Android and happens on devices and the simulator.

Is this normal behaviour? I have some ideas on how to work around it, but I'd like to avoid implementing them and keep the same code if I can, since it already works fine in iOS.

Thanks for your time.

ATTENTION."Package restored using NETFramework v4.6.1, instead of project target framework netstn

$
0
0

How do I solve this warning, which I believe is causing my application to crash on start. I can not change my project target framework to .NETFramework version v4.6.1 because it is not an option, the only things I can set as my project target framework is .netstandard 2.0 and less

NU1701 Package 'Microsoft.Net.Http 2.2.29' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETStandard,Version=v2.0'. This package may not be fully compatible with your project.

Show the image in full screen on tap of Listview image

$
0
0

Dears,

I have an image in my listview. For that image, I set Aspect="AspectFill".

On tap of that image, I need to view the image in full screen and the background will be a blur.

My requirement is like the initial tap of WhatsApp dp. In WhatsApp, On initial tap of dp full-screen image showing on top of WhatsApp contacts.

Thanks in advance.

Image Disappeared in Grid after tapping in iOS , don't care about Android for now

$
0
0

Hello Folks,

I'm trying to figure out one issue where image disappeared after tapping it on grid. Basically I'm using rg.plugins popup to pop up an image while tapping it on grid. Please take a look at screen shots and code. Any idea what's happening? Where I'm making mistakes?

ScreenShots:



Code Behind :
private async void BtnPhoto_Clicked(object sender, EventArgs e)
{
byte[] imageAsBytes;
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("No Camera", ":( No camera avaialble.", "OK");
return;
}

            var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions() { });

            if (file == null) return;

            var alpha = new Image
            {
                Source = ImageSource.FromStream(() => { return file.GetStream(); }),
                WidthRequest = 200,
                HeightRequest = 200
            };

            if (col == 0) grdLayout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(200, GridUnitType.Absolute) });

            grdLayout.ColumnDefinitions.Add(new ColumnDefinition
            {
                Width = new GridLength(200, GridUnitType.Absolute)
            });

            grdLayout.Children.Add(alpha, col, row);
            col++;
            if (col == 2) { col = 0; row++; }

            using (var memoryStream = new MemoryStream())
            {
                file.GetStream().CopyTo(memoryStream);
                file.Dispose();
                imageAsBytes = memoryStream.ToArray();
            }

            //Insert photos in DB and fetch info from DB at same time
            //Store images in byte array, then upload to Grid

            await App.FrendelSOAPService.InsertInstallerImages(CSID, imageAsBytes, RoomNo, RoomName);
        }

        public async void GetInstallerImages(){
            indicator.IsRunning = true;
            indicator.IsVisible = true;
            grdLayout.Children.Add(indicator, 0, 0);
            Grid.SetColumnSpan(indicator, 2);
            byte[][] lstByteArryImages = await App.FrendelSOAPService.GetInstallerImages(RoomNo);
            TotalImages = lstByteArryImages.Count();

            foreach(var imageBytes in lstByteArryImages){
                var newImage = new Image
                {
                    Source = ImageSource.FromStream(() => new MemoryStream(imageBytes)),
                    WidthRequest = 200,
                    HeightRequest = 200
                };
                TapGestureRecognizer tapGestureRecognizer = new TapGestureRecognizer
                {
                    Command = new Command(OnGridImageTapped),
                    CommandParameter = newImage
                };
                newImage.GestureRecognizers.Add(tapGestureRecognizer);

                if (col == 0) grdLayout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(200, GridUnitType.Absolute) });

                grdLayout.ColumnDefinitions.Add(new ColumnDefinition
                {
                    Width = new GridLength(200, GridUnitType.Absolute)
                });

                grdLayout.Children.Add(newImage, col, row);
                col++;
                if (col == 2) { col = 0; row++; }

            }

            //Calculation for Rows
            if (TotalImages % 2 == 0) row = TotalImages / 2;
            else { 
                row = (TotalImages / 2) + 1;
                col = 1;
                row--; //row always starts from 0, so if row = 2 it means starts from (0, 1) = 2 , same like index
            }
            indicator.IsRunning = false;
            indicator.IsVisible = false;
            btnCamera.IsEnabled = true;
        } //End of Method

        private async void OnGridImageTapped(object obj)
        {
            Image img = new Image();
            img = obj as Image;
            img.WidthRequest = 400;
            img.HeightRequest = 500;
            img.Aspect = Aspect.AspectFill;

            await PopupNavigation.Instance.PushAsync(new ImagePopUp(img));
            //await Navigation.PushPopupAsync(new ImagePopUp(img));
        }

Image Pop Up XAML File :

`<?xml version="1.0" encoding="utf-8" ?>
<pages:PopupPage 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"
         xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations;assembly=Rg.Plugins.Popup"
         x:Class="InstallerAppForms.ImagePopUp">
    <pages:PopupPage.Animation>
        <animations:ScaleAnimation 
            PositionIn="Center"
            PositionOut="Center"
            ScaleIn="1.2"
            ScaleOut="0.8"
            DurationIn="400"
            DurationOut="300"
            EasingIn="SinOut"
            EasingOut="SinIn"
            HasBackgroundAnimation="False"/>
    </pages:PopupPage.Animation>
    <StackLayout Padding="20, 20, 20, 20"
        VerticalOptions="Center" 
        HorizontalOptions="Center"
        x:Name="slImagePopUp">

    </StackLayout>
</pages:PopupPage>`

Image Pop Up Code Behind :

`public partial class ImagePopUp : PopupPage
    {
        public ImagePopUp(Image img)
        {
            InitializeComponent();
            slImagePopUp.Children.Add(img);
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();
        }

        protected override void OnDisappearing()
        {
            base.OnDisappearing();
        }

        // ### Methods for supporting animations in your popup page ###

        // Invoked before an animation appearing
        protected override void OnAppearingAnimationBegin()
        {
            base.OnAppearingAnimationBegin();
        }

        // Invoked after an animation appearing
        protected override void OnAppearingAnimationEnd()
        {
            base.OnAppearingAnimationEnd();
        }

        // Invoked before an animation disappearing
        protected override void OnDisappearingAnimationBegin()
        {
            base.OnDisappearingAnimationBegin();
        }

        // Invoked after an animation disappearing
        protected override void OnDisappearingAnimationEnd()
        {
            base.OnDisappearingAnimationEnd();
        }

        protected override Task OnAppearingAnimationBeginAsync()
        {
            return base.OnAppearingAnimationBeginAsync();
        }

        protected override Task OnAppearingAnimationEndAsync()
        {
            return base.OnAppearingAnimationEndAsync();
        }

        protected override Task OnDisappearingAnimationBeginAsync()
        {
            return base.OnDisappearingAnimationBeginAsync();
        }

        protected override Task OnDisappearingAnimationEndAsync()
        {
            return base.OnDisappearingAnimationEndAsync();
        }

        // ### Overrided methods which can prevent closing a popup page ###

        // Invoked when a hardware back button is pressed
        protected override bool OnBackButtonPressed()
        {
            // Return true if you don't want to close this popup page when a back button is pressed
            return base.OnBackButtonPressed();
        }

        // Invoked when background is clicked
        protected override bool OnBackgroundClicked()
        {
            // Return false if you don't want to close this popup page when a background of the popup page is clicked
            return base.OnBackgroundClicked();
        }

    }`

Dedicated Barcode Scanners in Xamarin Forms

$
0
0

I have been looking for a solution to use dedicated barcode scanners (so, NO camera scanning) connected either through bluetooth or USB (to a docking station) with an Android, iOS (maybe also UWP) tablet or phone device. And to my deep disappointment, it appears impossible to find information that is helping. Most suggestions talk about supporting Android, others about using ZXing library which uses camera to scan meaning it is dead slow to do scanning that way as camera needs to be loaded, then to focus on a barcode in order to scan it. That sometimes takes seconds.

ZXing might be great for individual users, regular phone/tablet user scanning only once in a while. Camera scanning is great that way but for business use, where users maybe scanning one or more items per second, ZXing and in general, camera scanning is not an option.

So, what is left? Based on my experience working with handheld ruggedized device, another option would be vendor SDKs or EMDKs. These are either free or you have to buy them. However, these are currntly available only for Android (Honeywell, Motorola, Intermec, Zebra, all of them support only Android or Xamarin Android. There is no support for Xamarin.Forms, Xamarin.iOS, Xamarin.UWP, not to mention .NET Standard 2, ...) (believe me on this, I have spent a week talking to all these vendors).

How about Nuget packages, PCL libraries, whatever? Well, turns out these are also available only for Android or Xamarin Android. Again dead end.

Then I read somewhere that scanners are just input devices, just like keyboards. Why not treat them as such and simply process key inputs using events such as TextChaned and Completed on an Xamarin.Forms Entry field. This is apparently called keyboard emulation.

This seem to be quite possible. No SDKs or EMDKs needed, no need to deal with 3rd party vendors, updates, being behind the host platform, no need to track different packages for different vendors and waste so much time, no need to bloat size of your app with packages you dont even know what they are doing.

This all makes perfect sense and the only possible dissadvantages of this method I can see are:

  • 2 input streams (keyboard and scanner) and how to distinguish btw them
  • possible need to configure a scanner

However, I dont see these as a problem and here is why. Scanners can be configured to have a prefix and / or a suffix after every and each scan. That solves 1st possible disadvantage above. But it leads to second - scanners need to be configured to have this suffix and/or prefix. However, if you control the scanners (deliver them to your customers), or if you can request or provide means to your customer to set this scanner configuration, which in my experience is mostly the case, then that is not a problem either.

My question is has anyone done this already?

I havent. I am in process of researching the option and I am thinking to give it a try but I do not see any issue with this idea. I admit, I have seen some saying that keyboard emulation is not good idea but I have also heard others swear into it. While the opposers havent provided any valuable explanation why keyboard emulation is a bad idea, everything I wrote above sounds to me a very logical and reasonable explanation why it is a great idea.

Please share your thoughts or solution if you have it and please dont read just the subject line and pollute this post with suggestions to use ZXing camera scanning or an SDK based solution for Android only, Xamarin is after all a cross-platform framework.

Xamarin.Forms - how can I get geo coordinates ?

$
0
0

I am trying to get current coordinates directly in Xamarin.Forms app in button click handler:
` LocationManager LocMgr = Android.App.Application.Context.GetSystemService("location") as LocationManager;
var locationCriteria = new Criteria();

        locationCriteria.Accuracy = Accuracy.High;
        locationCriteria.PowerRequirement = Power.High;
        var locationProvider = LocMgr.GetBestProvider(locationCriteria, true);
        var lastLocation = LocMgr.GetLastKnownLocation(locationProvider);

`

But it throws TimeoutException at locationCriteria.Accuracy = Accuracy.High. What am I doing wrong with my code and how to do this in a correct way?


Xamarin form webview with launch third party application

$
0
0

Hi, I'm new to xamarin form, currently i'm working on the xamarin form project and I successful implement the website into the webview !
**But now my issue was the third party application launch issue, it was fine while I browse on the Google browser. **
Example like the website having the phone dialer function, wherever mobile user browse the website and click on the phone number which can navigate user to the phone dialer on their own device.

While testing on my application instead of the web browser, it giving the error message like the below attachment.

After online searching there are not information suitable for my case, may I know what is the solution to overcome my issue, thank you in advance if there anybody provide some advise for me.

Data deleted after crashing the app

$
0
0

After crashing Xamarin forms android mobile app,database table data deleted.
how to solve this?

Page throws an error on android. I want to know what causes this error?

$
0
0

My project get crashed on displaying some pages in android only. I got a device log where I can't able to find the root of this issues. Please someone help me.

Here is my device log.
[Mono] Found as '__android_log_print'.
[MonoDroid] UNHANDLED EXCEPTION:
[MonoDroid] System.NullReferenceException: Object reference not set to an instance of an object
[MonoDroid] at Xamarin.Forms.Platform.Android.Platform.Xamarin.Forms.Platform.Android.IPlatformLayout.OnLayout (Boolean changed, Int32 l, Int32 t, Int32 r, Int32 b) [0x000a7] in :0
[MonoDroid] at Xamarin.Forms.Platform.Android.PlatformRenderer.OnLayout (Boolean changed, Int32 l, Int32 t, Int32 r, Int32 b) [0x0000e] in :0
[MonoDroid] at Android.Views.ViewGroup.n_OnLayout_ZIIII (IntPtr jnienv, IntPtr native__this, Boolean changed, Int32 l, Int32 t, Int32 r, Int32 b) [0x00009] in /Users/builder/data/lanes/2098/3efa14c4/source/monodroid/src/Mono.Android/platforms/android-23/src/generated/Android.Views.ViewGroup.cs:4044
[MonoDroid] at (wrapper dynamic-method) System.Object:5ad367da-5001-440b-94b9-f4a74e5e0e21 (intptr,intptr,bool,int,int,int,int)

ERROR : XF requires .NETFramework >= v4.7. You have 'v4.6.1'

$
0
0

hi everyone!!! i am getting this error when i am building my project. i have installed framework 4.7 in my visual studio but still project is targeting framework '4.6.1'. i don't know what to do?

[XF] Could not load assembly System.Buffers 4.0.2.0 on Android

$
0
0

I've been trying to use EF Core in a test project, but unfortunately I get an error at build time.
I've been consulting this guide

As soon as I add the Microsoft.EntityFrameworCore and Microsoft.EntityFrameworCore.Sqlite I get the following error

Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'System.Buffers, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. Perhaps it doesn't exist in the Mono for Android profile?
File name: 'System.Buffers.dll'
   at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(AssemblyNameReference reference, ReaderParameters parameters)
   at Xamarin.Android.Tasks.ResolveAssemblies.AddAssemblyReferences(DirectoryAssemblyResolver resolver, ICollection`1 assemblies, AssemblyDefinition assembly, Boolean topLevel)
   at Xamarin.Android.Tasks.ResolveAssemblies.Execute(DirectoryAssemblyResolver resolver)   EFCore.Android          

Am I missing something ? It behaves as if System.Buffers is required on Android, installing the nuget makes the error go away but I'm not sure if it's an okay workaround.

Edit
I'm using XF 3.1.0.697729
27.0.2.1 for android

Thanks,

Viewing all 77050 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>