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

Sharing a video or file to twitter

$
0
0

Can any one help me on this, While sharing a file or video from xamarin forms app to twitter it is sharing as a text but need to send as a link. How can i achieve that . Please help me. Thanks in advance.


XAML: Add circle below another circle

$
0
0

Hi there
I am using some nice Circle Progress Bar control: https://github.com/jsuarezruiz/MyTripCountdown/blob/master/src/MyTripCountdown/MyTripCountdown/Controls/CircleCountdown.cs

and in my XAML I am putting a label inside it

<?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:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="MyApp.Views.SomeInfo"
             xmlns:vm="clr-namespace:MyApp.ViewModels"
             xmlns:controls="clr-namespace:MyApp.Controls"
             Title="{Binding Title}">

    <!-- You need this so compiler knows where to find View Model for this file -->
    <ContentPage.BindingContext>
        <vm:BoardInfoViewModel />
    </ContentPage.BindingContext>

    <ContentPage.Content>
        <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*" />

                </Grid.RowDefinitions>
            <Grid Grid.Row="1">
                    <!-- Work Time -->
                    <Label Text="Some Text in the center of the ring"
                     VerticalOptions="CenterAndExpand" 
                     HorizontalOptions="CenterAndExpand" 
                     Margin="12"
                     Font="Bold,40" />
                    <!-- Work Countdown circle -->
                    <controls:CircleCountdown 
                        VerticalOptions="FillAndExpand"
                        HorizontalOptions="FillAndExpand"
                        Progress="0.50"
                        ProgressStartColor="#DB1D8B"
                        ProgressEndColor="#5098CD"
                        StrokeWidth="10"/>
                </Grid>
            </Grid>
    </ContentPage.Content>
</ContentPage>

as you can see from the picture while this counter counts down there is nothing below it so How can I add some grey Circle below this pink/blue one so when pink/blue circle is dissaphearing it will show the below grey circle?

Also if anyone has any Idea how would I position the whole circle+text on the vertical center of a screen that would be great too

Thanks for Anwsering and Best Regards

Can't change ContentView in MessagingCenter callback

$
0
0

Hi,

XF Version 4.4.0.991640

I have a MessagingCenter subscription that calls a function that changes the content of my ContentView when a message has been received. This function runs, but when changing the content in this function:

    StackLayout assetContentStack = new StackLayout();
    [Code that adds views to the assetContentStack]
    AssetEntryView.Content = assetContentStack;

the MessagingCenter.Send throws this exception:

at System.Reflection.RuntimeMethodInfo.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00081] in /Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/external/mono/mcs/class/corlib/System.Reflection/RuntimeMethodInfo.cs:409 
  at System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) [0x00000] in /Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/external/mono/external/corefx/src/Common/src/CoreLib/System/Reflection/MethodBase.cs:53 
  at Xamarin.Forms.MessagingCenter+Subscription.InvokeCallback (System.Object sender, System.Object args) [0x00064] in D:\a\1\s\Xamarin.Forms.Core\MessagingCenter.cs:94 
  at Xamarin.Forms.MessagingCenter.InnerSend (System.String message, System.Type senderType, System.Type argType, System.Object sender, System.Object args) [0x0006b] in D:\a\1\s\Xamarin.Forms.Core\MessagingCenter.cs:217 
  at Xamarin.Forms.MessagingCenter.Xamarin.Forms.IMessagingCenter.Send[TSender] (TSender sender, System.String message) [0x00013] in <64598914a1374c2fa65e161f1f4b5185>:0 
  at Xamarin.Forms.MessagingCenter.Send[TSender] (TSender sender, System.String message) [0x00005] in <64598914a1374c2fa65e161f1f4b5185>:0 
  at Smartie.NfcImplementation.DidDetect (CoreNFC.NFCNdefReaderSession session, CoreNFC.NFCNdefMessage[] messages) [0x00045] in /Users/chris/Projects/smartie-xamarin/Smartie.iOS/NfcImplementation.cs:68 

However if I take out the line:

    AssetEntryView.Content = assetContentStack;

It works fine.
So I guess my question is: is there something I'm doing wrong? Can I not change the content view content in the messaging centre callback? I'm pretty sure this used to work...

I can post more code if needed.

Multi line text in grid cell

$
0
0

How to display text in a multi-line view in a single cell of a grid? say,

firstname
lastname
dob

All these needs to appear in a single cell, with different layout customisation for each line. Can this be done?

How do I hide the Tabs of TabbedPage when clicking a nested NavigationPage?

$
0
0

There is this great article on how to set up a TabbedPage:
https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/navigation/tabbed-page

It shows how a page of a tab can be set up with a NavigationPage, which of course shows a Back button on any of it's children - So far so good. BUT, it's majorly flawed!

Once you click to open a child of NavigationPage (which renders Back button), the tabs need to disappear! They don't. How do we hide the tabs?

Referring to the screen cap gif below: Say I have a couple static pages in a tab, and also one tab is a Navigation Page. If I click to a tab ("Schedule"), then click a navigation (child) to get to the child page ("Upcoming appointments"), it renders a back button as expected. BUT... the tabs are still visible! Now if you click another tab (like "Today" or "Settings") WHILE the child of "Schedule" tab is open, you get into a bad state where the back button does NOTHING. You have to click on the originating parent tab ("Schedule") before you can click back and dismiss the navigation child page.

ugh.... really? And this is an official example posted in the docs and sample files? Sheesh.

How do we fix this? How do we hide the tabs when the child NavigationPage is loaded and back button rendered?

Real world example of what I want:
Open Facebook on your phone, see tabs while viewing your feed. Tap on the Alert tab (bell icon) and tap a post, and you see the tabs disappear, the child page you navigated to takes the FULL screen and and the back button appears.

Why the aplication didn't install?

$
0
0

Hi everyone. I finished a App and then I did the process to make the apk, but when I try to install the apk in a android device, Appear the Message "
the application was not installed" I used Visual studio 2017

Formatted Label with Xamarin.Forms

$
0
0

Can someone please show me how to use Xamarin.Forms.Label.FormattedText correctly?

I'm using Xamarin.Forms to write a Carousel based app, when I try

Label IntroductionTextLabel = new Label(); IntroductionTextLabel.FormattedText = "Test";

I get this error:

"'Xamarin.Forms.Label' does not contain a definition for 'FormattedText' and no extension method 'FormattedText' accepting a first argument of type 'Xamarin.Forms.Label' could be found (are you missing a using directive or an assembly reference?)"

Perhaps it's the version of Xamarin I'm currently using...

The next step would be using this to display some HTML.

Thanks for any help.

Developing a Location Background Service

$
0
0

Hi

I want my app to send a location every x minuttes, both when using the app, but also when the app is in the background.

I seen a few example of how to create a service which is running in the background with xamarin.android. (https://github.com/xamarin/mobile-samples/tree/master/BackgroundLocationDemo)

But what about xamarin.forms, which I'm working on? Could the same code be used with forms? Also I haven't seen the same for xamarin.ios.

Why can't I find a full example code of sending locations from a app, both foreground and background? I'm convinced a lot of developers could be interested in such functionallity.

I'm very new to xamarin, so I'm hoping you can point me in the right direction if its possible to develop such funcionallity.

Kind regards


Handle android doze mode

$
0
0

I have an app that constantly send location to our server every 1 minute, everything work fine with the alarm manager setRepeating(). However once I unplugged the phone from power source and close my phone it enter doze mode then it stop sending location unless i wake up the phone manually , is there any way to let the phone continue the alarm even phone screen is off?

Xamarin - cocossharp freeze after lock/unlock

$
0
0

Good Morning,

I'm testing xamarin android. my app use cocossharp to animate some objects. When I put my app in the background and return it continues to function normally.

Add a video (link). As you can see, you can move a blank sheet that is a cocossharp feature, when you put the application in the background and get back to working normally:

https://drive.google.com/open?id=1PrJttcMgZFdtL9xfKHBaXajNpnns5s33

Now please note this other video. This is working normally, including the cocossharp features. When locking and unlocking the app the cocossharp features freeze:

https://drive.google.com/open?id=1945OSvc9VM833B1iQiYlq6j7temC2cVT

How to let image resolution be 48x48 in horizontal stacklayout

$
0
0

I have a search bar, and then an image button right beside it in a StackLayout with Horizontal Orientation, like this:
<StackLayout Orientation="Horizontal"> <SearchBar Placeholder="Search" FontSize="Medium" HeightRequest="50"/> <ImageButton Source="image.png"></ImageButton> </StackLayout>

Now the image.png is a 48x48 image, and if my stacklayout isn't perfect, the image gets either stretched or squished sideways, depending on what the width of the searchbar is, and if I don't set the width to anything, the search bar just pushes the image off the screen. What can I do to make it so that the image takes up the amount of space it needs to, and then the search bar can come in?

Thanks!

edit: I forgot to mention an issue! The iOS image is 22x22, but the android image is 48x48 ******* So I don't know what I should do in this case.

App crashes after change of splash screen

$
0
0
After changing the starting screen to another png, the app crashes while loading. Nothing else was changed except the xamarin standard logo into another logo. The logo is a web png exported out of adobe cc

iOS Large title with Shell

$
0
0

Hi guys,

I'm playing with shell and i'm facing an issue when i try to put a large title on my content page (iOS).

According to the documentation https://docs.microsoft.com/fr-fr/xamarin/xamarin-forms/platform/ios/page-large-title, i can use
xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core" ios:NavigationPage.PrefersLargeTitles="true" or ios:Page.LargeTitleDisplay="Always" to make it work, but as i'm doing everything based on a Shell app, i only have contentPage and not NavigationPage

`

<TabBar>
    <Tab Title="1">
        <ShellContent ContentTemplate="{DataTemplate pages:Page1}"/>
    </Tab>
    <Tab Title="2">
        <ShellContent ContentTemplate="{DataTemplate pages:Page2}"/>
    </Tab>
</TabBar>

`

I try to set it directly in the code behind but i have the same result. And if i embedded my ShellApp in a navigationPage in the App.xaml.cs, i have a NavigationPage must have a root Page before being used. Either call PushAsync with a valid Page, or pass a Page to the constructor before usage exception. Does anyone manage to make it works?

Thanks !

How to solve (The type 'Worker' exists in both...) error?

$
0
0

Hi,

I have updated my Xamarin Forms to latest pre 4.5 and now I am getting:

**Error CS0433 The type 'Worker' exists in both 'Xamarin.Android.Arch.Work.Runtime, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Xamarin.AndroidX.Work.Runtime, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'
**

How can I fix this please?

Thanks,
Jassim

Edit code during debug session on Android

$
0
0

Hi guys! This seems to be a quite noobish problem, nonetheless, still encountering the issue...
Some details: Xamarin Forms, PCL, Android emulator.
Is there any way to edit the code during a debug session? Also, is there a way to step back in the code during debugging? I assume the target emulator is not capable do these things, or is it? I also have a physical Android phone, which might help the situation.


Open a Browser Window with Javascript on Xamarin.Forms

$
0
0

I have a Xamarin.Forms app. It includes a button like this:

xaml()
{
<Button x:Name="Buy_Button" Text="Satın Al" FontAttributes="Bold" TextColor="#e2e2e2" BackgroundColor="#2A52BE" FontFamily="Segoe UI" Grid.Column="2" Grid.ColumnSpan="1" Grid.RowSpan="1"  CornerRadius="5"  VerticalOptions="Start" HorizontalOptions="Center" FontSize="15.667" Grid.Row="0" Margin="0,10,10,0"  Clicked="Buy_Button_ClickedAsync" CommandParameter="{Binding  Buy_URL}" />`
}

I'm sending a URL link to click event for opening specific web page. Code is:

  private async void Buy_Button_ClickedAsync(object sender, EventArgs e)
    {
        Button btn = (Button)sender; // Coming button from click event handler.
        var buylink = btn.CommandParameter.ToString(); // Get the CommandParameter.
                                                       //  await DisplayAlert("Satın alma linki", buylink, "Anladım"); // Show the link.
        try // Uwp & iOS & Android
        {
            await Browser.OpenAsync(new Uri(buylink), BrowserLaunchMode.SystemPreferred); // Open url in-app browser for iOS & Android- native in UWP
        }
        catch (NotImplementedInReferenceAssemblyException ex) //Wasm falls here because lack of Xamarin.Essentials.
        {
            // await DisplayAlert("Hata", ex.Message, "Anladım"); // Show the info about exception.

            // Jint - nt is a Javascript interpreter for .NET which provides full ECMA 5.1 compliance and can run on any .NET platform. 
            //Because it doesn't generate any .NET bytecode nor use the DLR it runs relatively small scripts faster. 
            //https://github.com/sebastienros/jint

            var engine = new Engine();
            engine.SetValue("log", new Action<object>(Console.WriteLine));

            engine.Execute(@"function openurl() { log('" + buylink + "'); }; openurl(); ");
        }
    }

In UWP, Xamarin.iOS and Xamarin. Android this code is running via Xamarin.Esssentials:

 await Browser.OpenAsync(new Uri(buylink), BrowserLaunchMode.SystemPreferred); // Open url in-app browser for iOS & Android- native in UWP

However, my Xamarin.Forms app projected to WebAssembly code with Uno Platform, so this code block not running. As a result. I install Jint to Xamarin.Forms app. This catch block prints the link to Browser console, but no window.open function track in API reference:

 catch (NotImplementedInReferenceAssemblyException ex) //Wasm falls here because lack of Xamarin.Essentials.
            {
                // await DisplayAlert("Hata", ex.Message, "Anladım"); // Show the info about exception.

                       // Jint - nt is a Javascript interpreter for .NET which provides full ECMA 5.1 compliance and can run on any .NET platform. 
                //Because it doesn't generate any .NET bytecode nor use the DLR it runs relatively small scripts faster. 
                //https://github.com/sebastienros/jint

                var engine = new Engine();
                engine.SetValue("log", new Action<object>(Console.WriteLine));

                engine.Execute(@"function openurl() { log('" + buylink + "'); }; openurl(); ");
            }
        }

How can I open WebBrowser page on WASM via Javascript form Xamarin.Forms C# code? Thanks.

RelativeLayout in XAML

$
0
0

How do you make a relative layout view in XAML?

I cannot seem to find any documentation that gives examples of this.

Looking for a map tiling view

$
0
0

I'm looking for recommendations on a tiled map view that I can use to render a scrollable map with custom local tiles. I've been looking at Mapsui but it seems like overkill for what I need so I'm wondering if there are any others out there.

I have an indexed tile grid stored as images which I would want to render from the local device. Must be able to scroll and pan/rotate and ideally be able to place overlay icons.

Anything I should be looking at?

How do to REST API with xmarin.forms

$
0
0

Hi there

I have used RestSharp and wrapped an api into a nice NET Standard library
the library takes username, password and platform as arguments and then api outputs api key which library uses internally it also had data models in it

now it works fine, but I don't know how to integrate it into Xmarin.Forms, where to initiate it to be able to acsess its methods and its data from every xmarin.forms subpage (I am using a AppShell)

if we start with Shell Template that visual studio 2019 provides

should I initiate my API in AppShell.xaml.cs or in App.xaml.cs
but then if I do that in there how would I acsess it in for instance AboutPage View Model (I can make it static but this doesn't seem right and it wierd you have to call AppShell.myApi everytime you want to use an api)?

How would I access it in Xmarin.Android portion (I could use MessageCenter(but I can only call void methods with this I cannot(or don't know how) return data) or I could create some static classes in Xmarin.Forms portion, but I don't know if it is the right approach)

what is the best way to handle exeptions (for now my library only throws Exeption with message: throw new Exception("Message Here"))
API has errors like this:

200 - Request successful. More information is returned in json object. Object schema depends on method.
201 - Request successful. No result returned.
400 - Error occurred. Additional information provided in json response (ErrorResponse format: more info below)
401 - Authentication failure. There are two possible reasons: disabled API access or invalid ApiKey provided
403 - Access forbidden
404 - Invalid method URL
405 - HTTP method not allowed, please verify HTTP method of the request
429 - Too many requests in a given amount of time. API limits are 20 requests/second, 1500 requests/hour, 10000 requests/day
5xx - Something wrong happened in Calamari backend. Please wait a while and repeat your request. If error still occurs, drop us a line.

If status 4xx is returned, you can read additional information from returned json object.
{
"message": string,
"code": string,
"field": string
}

message - Human readable error explanation.
code - Error code. Possible value depends on method but there is few common error codes.
field - Which field of payload object caused error. NULL when error is not related to particular field

What is the best aproach to throw appropriate exeption for this, at the end I would like to show an alert to the user if exeption accures, so my library would trow 500Exeption for instance and user would get an error

how would I do this globally, so I don't need to wrap every button in try/catch block

All theese are more of a design questions that bother me and I don't know where to find anwsers to them, as I never saw an example with Xmarin.Forms and REST api that takes username/password api then sends api key which app uses in all subsequent API requests

Hopefully someone can give me some advice on all this, (particulary how to handle exeption and inform the user and where in the project to construct the api so I can easly acsess it from all subpages)

Thannks for Anwsering and Best Regards

Xamarin incrementing loop of chat bubble feature

$
0
0

I'm creating a chatbot app with Xamarin.Forms, when I send a message and the chatbot replies the chat bubbles kinda do this incrementing looping stack thing. The first reply has one response, the second one has two, the third one has three and so on.

I've been using a sorta obscure bot framework called Oscova Bot and after checking for an answer on their forums I think it has something to do with an event handler and it occuring more than once or something. Heres the C# code.

/// <summary>
    /// View model for the ChatbotPage.xaml
    /// </summary>
    public class ChatbotPageViewModel : BaseViewModel
    {
        /// <summary>
        /// A field for TextToSend
        /// </summary>
        private string _texttosend;

        /// <summary>
        /// An Instance of a new SIML Oscova Chatbot
        /// </summary>
        public OscovaBot chatbot;

        /// <summary>
        /// A collection/list of chat message items
        /// </summary>
        public ObservableCollection<ChatMessageModel> Messages { get; set; } = new ObservableCollection<ChatMessageModel>();

        /// <summary>
        /// The text that the user inputs
        /// </summary>
        public string TextToSend
        {
            get
            {
                return _texttosend;
            }

            set
            {
                if (_texttosend != value)
                {
                    _texttosend = value;

                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// A command for sending the users messages
        /// </summary>
        public ICommand SendCommand { get; set; }


        /// <summary>
        /// ChatPageViewModel Constructor
        /// </summary>
        public ChatbotPageViewModel()
        {
            SendCommand = new RelayCommand(Send);

            chatbot = new OscovaBot();
            var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MainPage)).Assembly;
            Stream stream = assembly.GetManifestResourceStream("BluePillApp.Helpers.nice.siml");

            chatbot.Import(XDocument.Load(stream));
            chatbot.Trainer.StartTraining();
        }

        /// <summary>
        /// This function sends a message
        /// </summary>
        public void Send()
        {
            if (!string.IsNullOrEmpty(TextToSend))
            {
                //This adds a new message to the messages collection
                Messages.Add(new ChatMessageModel() { Text = TextToSend, User = App.User });

                //This gets the chatbots response for each message
                chatbot.MainUser.ResponseReceived += async (sender, args) =>
                {
                    await Task.Delay(1500);
                    Messages.Add(new ChatMessageModel() { Text = args.Response.Text });
                };

                var result = chatbot.Evaluate(TextToSend);
                result.Invoke();

                //Removes the text in the Entry after message is sent
                TextToSend = string.Empty;
            }
        }
    }
Viewing all 89864 articles
Browse latest View live


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