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

Android Auto & iOS Car Play

$
0
0

Is it possible to develop c# Xamarin forms application for android auto and iOS car play. I would like to integrate this into our existing Xamarin forms apps.

I believe in the incoming iOS 12 that apple carplay is being opened up to third parties. I do not see any sample code or anybody talking about this for Xamarin forms.


iOS Xamarin.Forms 4.8 SR2 getting format_unknowndatetimeword when system location is wrong

$
0
0

I am getting System.FormatException Format_UnknownDateTimeWord for iOS 14 Xamarin format_unknowndatetimeword on startup when system language is not set to german.

How to fix this? UWP and Android works perfectly.

Thanks You
Agredo

Xamarin Forms: BaseContentPage and BackButtonBehavior Binding not working (Shell)

$
0
0

Hey guys,

I created my own BaseContentPage and created a BindableProperty for a custom BackButtonBehavior.
My goal is to change the standard backbutton icon and allow a custom BackButtonBehavior with own Commands.

My BaseContentPage looks like that:

    public class BaseContentPage : ContentPage
    {
        public static readonly BindableProperty CustomBackButtonBehaviorProperty =
            BindableProperty.Create(nameof(CustomBackButtonBehavior), typeof(BackButtonBehavior), typeof(BaseContentPage),
                                            null, defaultBindingMode: BindingMode.Default
                                            ,propertyChanged: OnBackButonBehaviorPropertyChanged);


        public BackButtonBehavior CustomBackButtonBehavior
        {
            get
            {
                if (GetValue(CustomBackButtonBehaviorProperty) == null)
                    return CreateDefaultBackButtonBehavior();
                else
                    return (BackButtonBehavior)GetValue(CustomBackButtonBehaviorProperty);
            }
            set { this.SetValue(CustomBackButtonBehaviorProperty, value); }
        }

        public BaseContentPage()
        {
            //Shell.SetBackButtonBehavior(this, CustomBackButtonBehavior);
        }

        private BackButtonBehavior CreateDefaultBackButtonBehavior()
        {
            Application.Current.Resources.TryGetValue("FontAwesomeSolid", out var fontAwesomeSolid);

            var behavior = new BackButtonBehavior()
            {
                Command = new Command(async () =>
                {
                    await Shell.Current.GoToAsync("..");
                }),
                IconOverride = new FontImageSource()
                {
                    FontFamily = ((OnPlatform<string>)fontAwesomeSolid).Platforms.FirstOrDefault(p => p.Platform[0] == Device.RuntimePlatform).Value.ToString(),
                    Glyph = Controls.FontAwesomeSolid.IconConstants.ChessPawn,
                    Size = 22,
                    Color = Color.White
                },
            };

            return behavior;
        }

        static void OnBackButonBehaviorPropertyChanged(BindableObject bindable, object oldValue, object newValue)
        {

        }
    }

I use it for a new Xaml Page, which looks like that:

<?xml version="1.0" encoding="utf-8" ?>
<d:BaseContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                   xmlns:d="clr-namespace:IncomingDocumentApp.Controls"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="xxxx.Views.NewItemPage.NewItemPage"
             xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core" 
             ios:Page.UseSafeArea="true"
             Title="New Item"
             Visual="Material">

than i tried to set the BackButtonBehavior:

   <d:BaseContentPage.CustomBackButtonBehavior>
        <BackButtonBehavior Command="{Binding GoBackCommand}"
                            IsEnabled="True"/>
    </d:BaseContentPage.CustomBackButtonBehavior>

However, it the CustomBackButtonBehaviorProperty is never called.
The Binding is defined in the codebehind of the NewItemPage right after the InitializeComponent() call.

Any help would be appreciated!

snoova

Change cursor color in entry

$
0
0

Hi guys,

I want to change the cursor color in an entry to white, how can I do this? I tried a lot..;(

Custom sound from FCM Notification?

$
0
0

Is there any way to play custom sound on notification receive(firebase notification) for both iOS and Android?(even if app is closed).

How can I create a new PDF in Xamarin.forms? / ¿Como puedo crear un nuevo PDF en Xamarin.forms?

$
0
0

I am developing a new App which when the user complete all his tasks he has to press a button to confirm the realized activity, after that the App have to create a PDF which will be sended by e-mail.
My problem is when I want to create the PDF. I found a lot of libraries on internet but none of them is working for me.

Can someone tell me which one is the easiest to use and give me an example?

Thanks!


Estoy desarrollando una nueva App en la que el usuario al finalizar todas sus tareas debe apretar un botón para confirmar la actividad realizada, luego de esto se generará un PDF el cual será enviado por e-mail.
El problema lo tengo cuando quiero crear el PDF ya que busqué muchas librerías por internet pero ninguna me está funcionando.

Alguien podría decirme cual es la mas sencilla de usar y pasarme algun ejemplo?

Gracias!

getting white screen while navigate to another page

$
0
0

while navigating a page to another page sometime content page showing white screen, after rotate my device then content appears

how to solve this in my xamarin forms app?

Next Xamarin.Forms 4.8 Release Date

$
0
0

When will the next version (after 4.8.0.1451) of Xamarin.Forms 4.8 be released?


Problems to use Plugin.BLE in Android 10

$
0
0

Hi guys. My name is Felipe i'm from Brazil.

Try to use Plugin.BLE but works only iOS and Android 8 or bottom.
The problem is on call await characterist.StartUpdateAsync(). On call this method in Android 10 the code skip the rest.

Someone help me?

This is my code:

if (device != null)
            {
                await adapter.StopScanningForDevicesAsync();
                //await adapter.DisconnectDeviceAsync(device);
                await adapter.ConnectToDeviceAsync(device);

                var services = await device.GetServicesAsync();

                ICharacteristic characteristicTemperature = null;
                ICharacteristic characteristicBattery = null;

                foreach (var service in services)
                {
                    var caracteristicas = await service.GetCharacteristicsAsync();


                    foreach (var carac in caracteristicas)
                    {

                        var descritors = await carac.GetDescriptorsAsync();

                        //Bug android 9 ou > -- Problemas ao notificar o device
                        //Checa se é Bateria ou Temperatura
                        if (carac.Uuid == "2a19" || carac.Uuid == "2a1c"
                            || carac.Name.ToLower().Equals("temperature measurement")
                            || carac.Name.ToLower().Equals("battery level"))
                        {

                            if (carac.Name.ToLower().Equals("battery level") || carac.Uuid == "2a19")
                            {
                                characteristicBattery = carac;
                            }

                            if (carac.Name.ToLower().Equals("temperature measurement") || carac.Uuid == "2a1c")
                            {
                                characteristicTemperature = carac;
                            }

                        }
                    }
                }


                if (characteristicTemperature.CanUpdate)
                {
                    characteristicTemperature.ValueUpdated += (o, args) =>
                    {
                        byte[] bytes = args.Characteristic.Value;
                    };

                    await characteristicTemperature.StartUpdatesAsync();

                }


                if (characteristicBattery.CanUpdate)
                {
                    characteristicBattery.ValueUpdated += (o, args) =>
                    {
                        byte[] bytes = args.Characteristic.Value;
                    };

                    await characteristicBattery.StartUpdatesAsync();

                }

                //Temperatura
                if (characteristicTemperature.Uuid == "2a1c" || characteristicTemperature.Name.ToLower().Equals("temperature measurement"))
                {

                    byte[] byteValues = characteristicTemperature.Value;

                    if (byteValues.Length > 0)
                    {

                        string hexadecimal = BitConverter.ToString(byteValues);
                        string[] hexSplit = hexadecimal.Split('-');

                        //Temperatura
                        string medicaoHex = "0x" + hexSplit[2] + hexSplit[1];
                        string result = Convert.ToInt32(medicaoHex, 16).ToString();
                        string temperatura = result.Substring(0, 2) + "," + result.Substring(2, 2);

                        //Horário
                        string horaHex = "0x" + hexSplit[9];
                        string minutoHex = "0x" + hexSplit[10];
                        string segundoHex = "0x" + hexSplit[11];

                        int hora = Convert.ToInt32(horaHex, 16);
                        int minuto = Convert.ToInt32(minutoHex, 16);
                        int segundo = Convert.ToInt32(segundoHex, 16);
                        TimeSpan horario = new TimeSpan(hora, minuto, segundo);

                        temperature.Text = temperatura + "º";

                        titleTemperature.Text = "Ultima medição em " + minuto + " minutos";

                        activeLoad.IsRunning = false;
                        activeLoad.IsVisible = false;

                        frameTemperature.IsVisible = true;
                    }
                }

                if (characteristicBattery.CanRead)
                {
                    if (characteristicBattery.Uuid == "2a19" || characteristicBattery.Name.ToLower().Equals("battery level"))
                    {
                        byte[] byteValues = characteristicBattery.Value;
                        string hexadecimal = BitConverter.ToString(byteValues);
                        int batteryLevel = 0;
                        if (!string.IsNullOrEmpty(hexadecimal))
                        {
                            string[] hexSplit = hexadecimal.Split('-');

                            //Bateria
                            string batteryHex = "0x" + hexadecimal;
                            batteryLevel = Convert.ToInt32(batteryHex, 16);
                        }


                        lblBattery.Text = "Nível de bateria: " + batteryLevel + "%";

                    }


                }



            }

How I can copy my Sqlite database from Device to PC?

$
0
0

How I can copy my Sqlite database from Device to PC?

List View : How to find selected item when there are duplicates

$
0
0

Hello,

I'm new to Xamarin and mobile app development.
I've always used lstItems.SelectedIndex to find the selected item when there are duplicate items in a list. But with Xamarin.forms, this doesn't seem to be an option. I am very new (as of this morning..) to using view models and binding. I think I get the basic idea, but I'm very stuck and need some guidance.

Lets assume the list is named lstItems. There may be multiple of the same items on the list. How can I tell which item has been selected?

Thank you in advance.

How fix this problem?

$
0
0

I want to create custom TabbedPage, but I have error: System.NullReferenceException: 'Object reference not set to an instance of an object.'

How I can fix it?

This is my custom TabbedPage code:

[assembly: ExportRenderer(typeof(CustomTabbedPage), typeof(CustomTabbedPageRenderer))]
namespace App.Droid.CustomRenders
{
[Obsolete]
class CustomTabbedPageRenderer : TabbedRenderer
{
Xamarin.Forms.TabbedPage tabbedPage;
BottomNavigationView bottomNavigationView;
Android.Views.IMenuItem lastItemSelected;
private bool firstTime = true;
int lastItemId = -1;
public CustomTabbedPageRenderer(Context context) : base(context)
{
}

    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.TabbedPage> e)
    {
        base.OnElementChanged(e);

        if (e.NewElement != null)
        {
            tabbedPage = e.NewElement as CustomTabbedPage;
            bottomNavigationView = (GetChildAt(0) as Android.Widget.RelativeLayout).GetChildAt(1) as BottomNavigationView;
            bottomNavigationView.NavigationItemSelected += BottomNavigationView_NavigationItemSelected;

            //Call to remove animation
            SetShiftMode(bottomNavigationView, false, false);

            //Call to change the font
            ChangeFont();
        }

        if (e.OldElement != null)
        {
            bottomNavigationView.NavigationItemSelected -= BottomNavigationView_NavigationItemSelected;
        }


    }

    //Change Tab font
    void ChangeFont()
    {
        var fontFace = Typeface.CreateFromAsset(Context.Assets, "gilsansultrabold.ttf");
        var bottomNavMenuView = bottomNavigationView.GetChildAt(0) as BottomNavigationMenuView;

        for (int i = 0; i < bottomNavMenuView.ChildCount; i++)
        {
            var item = bottomNavMenuView.GetChildAt(i) as BottomNavigationItemView;
            var itemTitle = item.GetChildAt(1);

            var smallTextView = ((TextView)((BaselineLayout)itemTitle).GetChildAt(0));
            var largeTextView = ((TextView)((BaselineLayout)itemTitle).GetChildAt(1));

            lastItemId = bottomNavMenuView.SelectedItemId;

            smallTextView.SetTypeface(fontFace, TypefaceStyle.Bold);
            largeTextView.SetTypeface(fontFace, TypefaceStyle.Bold);

            //Set text color
            var textColor = (item.Id == bottomNavMenuView.SelectedItemId) ? tabbedPage.On<Xamarin.Forms.PlatformConfiguration.Android>().GetBarSelectedItemColor().ToAndroid() : tabbedPage.On<Xamarin.Forms.PlatformConfiguration.Android>().GetBarItemColor().ToAndroid();
            smallTextView.SetTextColor(textColor);
            largeTextView.SetTextColor(textColor);
        }
    }

    //Remove tint color
    protected override void OnLayout(bool changed, int l, int t, int r, int b)
    {
        base.OnLayout(changed, l, t, r, b);

        if (bottomNavigationView != null)
        {
            bottomNavigationView.ItemIconTintList = null;
        }

        if (firstTime && bottomNavigationView != null)
        {
            for (int i = 0; i < Element.Children.Count; i++)
            {
                var item = bottomNavigationView.Menu.GetItem(i);
                if (bottomNavigationView.SelectedItemId == item.ItemId)
                {
                    SetupBottomNavigationView(item);
                    break;
                }
            }
            firstTime = false;
        }

    }

    void BottomNavigationView_NavigationItemSelected(object sender, BottomNavigationView.NavigationItemSelectedEventArgs e)
    {
        var bottomNavMenuView = bottomNavigationView.GetChildAt(0) as BottomNavigationMenuView;
        var normalColor = tabbedPage.On<Xamarin.Forms.PlatformConfiguration.Android>().GetBarItemColor().ToAndroid();
        var selectedColor = tabbedPage.On<Xamarin.Forms.PlatformConfiguration.Android>().GetBarSelectedItemColor().ToAndroid();

        if (lastItemSelected != null)
        {
            lastItemSelected.Icon.SetColorFilter(normalColor, PorterDuff.Mode.SrcIn);

        }

        if ($"{e.Item}" != "App")
        {
            e.Item.Icon.SetColorFilter(selectedColor, PorterDuff.Mode.SrcIn);
            lastItemSelected = e.Item;
        }

        if (lastItemId != -1)
        {
            SetTabItemTextColor(bottomNavMenuView.GetChildAt(lastItemId) as BottomNavigationItemView, normalColor);
        }

        SetTabItemTextColor(bottomNavMenuView.GetChildAt(e.Item.ItemId) as BottomNavigationItemView, selectedColor);


        SetupBottomNavigationView(e.Item);
        //this.OnNavigationItemSelected(e.Item);

        lastItemId = e.Item.ItemId;

    }


    void SetTabItemTextColor(BottomNavigationItemView bottomNavigationItemView, Android.Graphics.Color textColor)
    {
        var itemTitle = bottomNavigationItemView.GetChildAt(1);
        var smallTextView = ((TextView)((BaselineLayout)itemTitle).GetChildAt(0));
        var largeTextView = ((TextView)((BaselineLayout)itemTitle).GetChildAt(1));

        smallTextView.SetTextColor(textColor);
        largeTextView.SetTextColor(textColor);
    }


    //Adding line view
    void SetupBottomNavigationView(IMenuItem item)
    {
        int lineBottomOffset = 8;
        int lineWidth = 4;
        int itemHeight = bottomNavigationView.Height - lineBottomOffset;
        int itemWidth = (bottomNavigationView.Width / Element.Children.Count);
        int leftOffset = item.ItemId * itemWidth;
        int rightOffset = itemWidth * (Element.Children.Count - (item.ItemId + 1));
        GradientDrawable bottomLine = new GradientDrawable();
        bottomLine.SetShape(ShapeType.Line);
        bottomLine.SetStroke(lineWidth, Xamarin.Forms.Color.DarkGray.ToAndroid());

        var layerDrawable = new LayerDrawable(new Drawable[] { bottomLine });
        layerDrawable.SetLayerInset(0, leftOffset, itemHeight, rightOffset, 0);

        bottomNavigationView.SetBackground(layerDrawable);
    }


    //Remove animation
    public void SetShiftMode(BottomNavigationView bottomNavigationView, bool enableShiftMode, bool enableItemShiftMode)
    {
        try
        {
            var menuView = bottomNavigationView.GetChildAt(0) as BottomNavigationMenuView;
            if (menuView == null)
            {
                System.Diagnostics.Debug.WriteLine("Unable to find BottomNavigationMenuView");
                return;
            }
            var shiftMode = menuView.Class.GetDeclaredField("mShiftingMode");
            shiftMode.Accessible = true;
            shiftMode.SetBoolean(menuView, enableShiftMode);
            shiftMode.Accessible = false;
            shiftMode.Dispose();
            for (int i = 0; i < menuView.ChildCount; i++)
            {
                var item = menuView.GetChildAt(i) as BottomNavigationItemView;
                if (item == null)
                    continue;
                //item.SetShiftingMode(enableItemShiftMode);
                item.SetChecked(item.ItemData.IsChecked);
            }
            menuView.UpdateMenuView();
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"Unable to set shift mode: {ex}");
        }
    }
}

}

And my xaml code:

<var:CustomTabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

            NavigationPage.HasNavigationBar="False"
            xmlns:app="clr-namespace:App;"
                      xmlns:var="clr-namespace:App.CustomClasses"
             x:Class="App1.Pages.CarPage.TabbedMenu">
  <!--Pages can be added as references or inline-->
    <var:CustomTabbedPage.Children>
        <NavigationPage Title="Page1" BackgroundColor="White">
        <x:Arguments>
            <app:Page1 />
        </x:Arguments>
    </NavigationPage>
        <NavigationPage Title="Page2" BackgroundColor="White">
        <x:Arguments>
            <app:Page2 />
        </x:Arguments>
    </NavigationPage>
    </var:CustomTabbedPage.Children>
</var:CustomTabbedPage>

CarPlay using Xamarin forms

$
0
0

can we implement car play in iOS using Xamarin forms. is there any sample or documentation available for the same ?

How to use XML (Android Vector Drawable ) for images on Android and SVG for IOS?

$
0
0

Hi
I currently use XML (android vector drawables) for images in the resources/drawable folder for Android.
That works fine.
I want to use SVG's for IOS however when i place SVG's inside the resources folder with the same file name, it doesn't work. PNG's work fine. but i want to use SVG's as they are higher quality.
I've also tried using FFsvgcachedimage but that stops android from working but IOS then works fine.
Has anyone implemented SVG's and Android Vectors in Xamarin forms before?
Thanks

AutoSize Label with a Formatted Text not working on Android

$
0
0

I am trying to implement autofit functionality to the label, i.e. reduce the font size of the label to fit in the same line. Tried using effects and custom renderers as well. Works fine on iOS but not on Android because i am using Formatted text property in the Label.

I have posted detailed information on this issue here - https://stackoverflow.com/questions/64120955/autosize-label-with-a-formatted-text-not-working-on-android

Also, is it possible to change the font family of a specific word in a Label without using formatted text? because eliminating the use of formatted text could resolve the issue with autofit renderer/effect.

Any suggestions would be of great help. Thank you in advance.


Tag Friends In Xamarin Forms

$
0
0

Hi Guys,
I have an requirement for tagging multi friends with their profile picture . For Example i have an 100 friends in my friends list, i need to tag 50 friends for single post . How i will achieve this ?

Get a font exception if not in Navigation page

$
0
0

I had a Xamarin.Forms application which had a tool bar, so the MainPage was wrapped with a Navigation page (for having
this tool bar). Everything worked well.

Now, I try to convert this application to be a MasterDetail Page application.
Therefore I don't need the Navigation page (If I use the Navigation Page I will have two toolbars, and I don't want it).

The problem is that when I launch MasterDetailPage not wrapped with a Navigation page (From App.cs)
I get the exception:
" Java.Lang.RuntimeException: 'Font asset not found sans-serif' "
in MainActivity.cs

I've checked in all the solution: I don't use any font with the name 'sans-serif'.

for summary:~~~~
In App.xaml.cs:
MainPage = new NavigationPage(new NiceMasterDetailPage());
doesn't provide any exception.

In App.xaml.cs:
MainPage = new NiceMasterDetailPage();
does provide the exception:
" Java.Lang.RuntimeException: 'Font asset not found sans-serif' "

Does someone can help me understand why?

How to implement this in xamarin. Login the app using the web dashboard

$
0
0

okay guys title says it all. I have a client with an existing system, they have a web dashboard like this

now the system have total control to the app when they want to log in the mobile app the app will get some data from the web API. the web api register the IMEI of the mobile then once the imei is registered the app can now get some data from the web API. Its a delivery app with a dispatcher>rider system

Error on saving sqlite data

$
0
0

Hi
i create a simple User and NewCustomer class so defined:

 public class User {
       [PrimaryKey, AutoIncrement]
        public int Id { get; set; }

        [Unique, MaxLength(255)]
        public string Name { get; set; }

        [Unique, MaxLength(255)]
        public string Password { get; set; }

        [Unique, MaxLength(255)]
        public string Email { get; set; }

        [OneToMany(CascadeOperations = CascadeOperation.All)]
        public List<NewCustomer> NewCustomers { get; set; }
}

 public class NewCustomer
    {
        [PrimaryKey, AutoIncrement]
        public int Id{ get; set; }   
        public string Code { get; set; }
        public string Name{ get; set; }
        public string Due{ get; set; }
        ...

        [ForeignKey(typeof(User))]
        public int UserId { get; set; }

        [ManyToOne]
        public User User { get; set; }
}

When I save newCustomer I recive this error:
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

But when i open sqlite table i found all record correctly inserted in NewCustomer tables even UserId (FK to user)
so i do not understand what is wrong.

Tks for help
This is my first app so i need help

java.lang.InstantiationException Xamarin Forms Android Crash on start-up Error Debug R8 / ProGuard

$
0
0

Hi All
My app keeps crashing and i cant figure out how to properly debug. It's been released to the play store and I'm seeing numerous crashes and reports with the error java.lang.InstantiationException on the Play store.

Screenshot of the error is here.

I have a feeling its to do with the R8/ Proguard configuration but cannot nail down which class is causing the error or how to properly debug. I have tried Device-Logcat within Visual studio but that does not display the error. Starting the app in debug mode loads the app and just quits so no help there.

The error message is not helpful at all, and I do not want to disable PROGUARD/R8 as it helps with APK size and obfuscation.

Any ideas?

Viewing all 91519 articles
Browse latest View live


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