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

HtmlLabelConverter with multiple links not working.

$
0
0

Adam Pedley posted a nice solution for converting html to a Label https://xamarinhelp.com/hyperlink-in-xamarin-forms-label/?utm_campaign=Weekly+Xamarin&utm_medium=email&utm_source=Weekly_Xamarin_166.

I extended the converter a bit and remove some bugs. It now also converts bold and italic tags as well as br and p-tag. The problem I run into is that when there are multiple links the click gesture does not work. It only works when there is 1 link.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows.Input;
using Xamarin.Forms;

namespace LuisterrijkApp
{
    public class HtmlLabelConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Label label = null;  // label is used to set the FontSize for Bold and Italic
            if (parameter is Label) 
            {
                label = (Label)parameter;
            }

            var formatted = new FormattedString();

            foreach (var item in ProcessString((string)value))
            {
                if (item.Type == "b") 
                {
                    formatted.Spans.Add(CreateBoldSpan(item, label));
                }
                else
                if (item.Type == "i")
                {
                    formatted.Spans.Add(CreateItalicSpan(item, label));
                }
                else
                {
                    formatted.Spans.Add(CreateAnchorSpan(item));
                }
            }

            return formatted;
        }

        private Span CreateAnchorSpan(StringSection section)
        {
            var span = new Span()
            {
                Text = section.Text
            };

            if (!string.IsNullOrEmpty(section.Link))
            {
                span.GestureRecognizers.Add(new TapGestureRecognizer()
                {
                    Command = _navigationCommand,
                    CommandParameter = section.Link
                });
                span.TextColor = Color.Blue;
                // Underline coming soon from https://github.com/xamarin/Xamarin.Forms/pull/2221
                // Currently available in Nightly builds if you wanted to try, it does work :)
                // As of 2018-07-22. But not avail in 3.2.0-pre1.
                // span.TextDecorations = TextDecorations.Underline;
            }

            return span;
        }

        private Span CreateBoldSpan(StringSection section, Label label)
        {
            var span = new Span()
            {
                Text = section.Text,
                FontAttributes = FontAttributes.Bold
            };
            if (label != null)
            {
                span.FontSize = label.FontSize;
            }

            return span;
        }

        private Span CreateItalicSpan(StringSection section, Label label)
        {
            var span = new Span()
            {
                Text = section.Text,
                FontAttributes = FontAttributes.Italic
            };
            if (label != null)
            {
                span.FontSize = label.FontSize;
            }

            return span;
        }

        public IList<StringSection> ProcessString(string rawText)
        {
            rawText = rawText.Replace("<br>", "\n");
            rawText = rawText.Replace("<br/>", "\n");
            rawText = rawText.Replace("<br />", "\n");
            rawText = rawText.Replace("<p>", "\n");
            rawText = rawText.Replace("</p>", "\n");
            const string spanPattern = @"(<[abi].*?>.*?</[abi]>)";

            MatchCollection collection = Regex.Matches(rawText, spanPattern, RegexOptions.Singleline);

            var sections = new List<StringSection>();

            var lastIndex = 0;

            foreach (Match item in collection)
            {
                var foundText = item.Value;
                sections.Add(new StringSection() { Text = rawText.Substring(lastIndex, item.Index - lastIndex) });
                lastIndex = item.Index + item.Length;

                var html = new StringSection()
                {
                    Link = Regex.Match(item.Value, "(?<=href=\\\")[\\S]+(?=\\\")").Value,
                    Text = Regex.Replace(item.Value, "<.*?>", string.Empty),
                    Type = item.Value.Substring(1,1)
                };

                sections.Add(html);
            }

            sections.Add(new StringSection() { Text = rawText.Substring(lastIndex) });

            return sections;
        }

        public class StringSection
        {
            public string Text { get; set; }
            public string Link { get; set; }
            public string Type { get; set; }
        }

        private ICommand _navigationCommand = new Command<string>((url) =>
        {
            Device.OpenUri(new Uri(url));
        });

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }}

ActivityIndicator does not show AT ALL

$
0
0

I want to use a ActivityIndicator, basically for asynchronous actions to a server in a MVVM setup. I am trying that for the first time, it just won't go.

Now a lot could be wrong, but even in the SIMPLEST way it does not show AT ALL. I can see space is reserved on screen, but it stays invisible.
<ActivityIndicator Color="Black" IsVisible="True" IsRunning="True" IsEnabled="True" VerticalOptions="Center" HorizontalOptions="Center" HeightRequest="25" WidthRequest="25"/>
I have looked around on the web for any explanation or solution. But I gave up.

Is this a bug?

I have got Xamarin 4.2.2.11, Xamarin.Android 7.0.2.42.
Everything is up to date as far as I know.

Is it possible to use SQLLite (or any other DB) instance on PC and not Emulator

$
0
0

I believe it must be the most common requirement during development that one will need to make frequent changes to database and models etc. What I am looking for is that how I can use a local instance of a database on my desktop and not from emulator. I mean do I really have to copy time and again. I thought we will have a straight forward technique where the database will reside on my desktop. I will develop against this database and once done I will use adb shell to copy it to emulator and finally deploy it.

Expander is throwing error

$
0
0

Hi,

I am trying to use Expander View in one of my ContentPage but I am getting this error.

XLS0414 The type 'Expander' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built

I have also added this line in App.cs

Device.SetFlags(new string[] { "Expander_Experimental" });

CollectionView ScrollTo not working properly

$
0
0

I have horizontal CollectionView which have 30 items. If I put collectionview.ScrollTo(15) then it scrolls to the end of the collectionview instead of 15th index.

TEditor richtextbox not working

$
0
0

Hello guys i am trying to use https://github.com/SymplastLLC/TEditor
Is working on xamarin froms last release
This how i am trting to fire him but it is not working

 async private void Button_Clicked(object sender, EventArgs e)
        {
           await ShowTEditor();
        }

        async Task ShowTEditor()
        {
            TEditorResponse response = await CrossTEditor.Current.ShowTEditor("<p>XAM consulting</p>");
            if (!string.IsNullOrEmpty(response.HTML))
            {
                _displayWebView.Source = new HtmlWebViewSource() { Html = response.HTML };
            }
        }

CClark Plugin and Device Calendar Save works weird

$
0
0

Hi

I want to save appointments to the device calendar. (No need to get only save).

I use CClark Plugin

Firstly want to use the GCalendar, but there are so many discusson about the Google Calendar and everybody says its impossible to connect to Google Calendar from Xamarin.Forms, and i choosed other solution (but i am very Sad about the GCalendar)

Anyway, lets see the device calendar. I can create calendar, and get the id, but its strange when i want to save:

My code:

 public void MultipleAddOrUpdateAppointments(List<TestItem> testitemsList)
        {
            var items = TestItem.SaveToDeviceCalendar(testitemsList);
            foreach (CalendarEvent item in items)
            {
                CrossCalendars.Current.AddOrUpdateEventAsync(ownCalendar, item);
            }
        }

You can see, i have the full appointments in the items variable. So, I can't get any result. No Exception, No nothing, and in the device calendar i havent got any data.

I need to work, because there are no any support for recurring appointment, so thats why i created that way.

I gave permissions, read write too.

I dont know what is the problem, i create many ways to can save the appointments list to device calendar, but all result is the same.

  • Any idea whats wrong?

  • Or somebody can know an alternative plugin or way to save device calendar from Xamarin.Forms?

  • i would just like to ask quietly if anyone has found any solution for google calendar from xamarin.forms, that would be the best

Video Player inside CollectionView item addition causes video frame shuffle Xamarin Forms

$
0
0

I have a CollectionView that has a VideoPlayer element in its DataTemplate taken from Xamarin Forms sample projects. On iOS, the video player rendered uses AVPlayer to play video.
I also have a button that when pressed, adds more items to the ItemSource of the CollectionView.
If I play the first, say, three items and pause them all on random frame/time, and then press this add more items button, the frozen image frames on these three AVPlayer instances on iPhone get shuffled/switched in some weird order.
In more detail:

If the first item of the CollectionView has some animated cartoon video paused, and the second item has some sports game video paused, and the third item has some forest images video paused, when I press the add more items button, and some new items get added to the ItemSource of the CollectionView, I see the sports game video frame moved to the first item's AVPlayer instance, the forest images video frame moved to second item's AVPlayer instance and the animated cartoon frame is moved to third item's AVPlayer instance.
After these have been 'shuffled', if I unpause the first item, it plays its original video of animated cartoon, and same goes with item two and three. The only problem, as I understand it, is that somewhere in the caching / cell reusing mechanism of CollectionView, the cached frames of AVPlayer are switched in some order when new items are added to the CollectionView.
This problem happens exclusively with AVPlayer. Any other element, does not reproduce this behavior. I have tried with ffimageloading's CahcedImage, simple labels and other elements, but it is only AVPlayer's rendered, paused frame images that get shuffled.
I realize this issue probably has some deep roots that won't be solved on Xamarin Forms level, but just wanted to try my luck here.

My code for the CollectionView is pretty basic:

<CollectionView ItemsSource="{Binding ScrollArticles}" 

                AbsoluteLayout.LayoutBounds="0,0,1,1"
                AbsoluteLayout.LayoutFlags="All"
        RemainingItemsThreshold="5"
                RemainingItemsThresholdReachedCommand="{Binding LoadMoreItems}"
                VerticalOptions="FillAndExpand" 
                HorizontalOptions="FillAndExpand"
                ItemsLayout="VerticalList"
                x:Name="CategoryItemsListView"
                VerticalScrollBarVisibility="Always"
                Scrolled="CategoryItemsListView_OnScrolled"

                >

    <CollectionView.ItemTemplate>
        <DataTemplate>

                <elements:VideoPlayer Margin="0,0,0,15" Source={Binding video_url}>

                </elements:VideoPlayer>

        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

The same exact code, when having the VideoPlayer element replaced with any other element, say Image, behaves as it should.
Another thing is that the same exact VideoPlayer code does not do this when implemented inside ListView (with CachingStrategy=RecycleElement) instead of CollectionView. But unfortunately, ListView lacks a lot of features such as determining the center most item when scrolling etc.


Xamarin.Forms preview not working for iOS

$
0
0

Hello.

When opening a XAML file in the designer for iOS I get the error "An exception occurred while rendering the control" and, clicking the red exclamation point icon, "Could not load the file 'Xamarin.Forms.Platform.iOS'".

It loads and displays fine for Android.

The XAML page is the "AboutPage.xaml" that comes with the project templates.

I am able to compile, run, and deploy the iOS project both in the simulator and on my iPhone.

I'm using VS 2019 Community (16.6.0), Xcode 11.5, and Xamarin.Forms 4.6.0.800 (according to NuGet pkg manager).

I tried this and it did not resolve the issue: https://forums.xamarin.com/discussion/comment/410256#Comment_410256

Any help is greatly appreciated.

Mike

How to get index and id from SfRadioButton?

$
0
0

How to get index and id from SfRadioButton? I use sfradiobutton and need its index / id

Image height not auto adjust

$
0
0

Hello, I have an Image wich is located inside a Stacklayout (no height set). I would like to size the image to 100% width of the Stacklayout and the height dynamically.
I've tried all Aspect possibilities and it is not working. With option "AspectFill" the Image is cut off.


Any suggestions?
Thanks.

Dirk

When using xamarin.forms.Pancake causes the app to crash

$
0
0

When I try to navigate to a page with Pancake view, It causes the app to crash with an error

"Attempt to invoke virtual method 'void android.graphics.Bitmap.setHasAlpha(boolean)' on a null object reference'".

Below is the sample text. Note as soon as I remove Pancake view it renders perfectly.

<pancakeview:PancakeView BackgroundColor="{StaticResource WhiteColor}" CornerRadius="6">
                    <Grid RowSpacing="0">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*" />
                            <RowDefinition Height="Auto" />
                            <RowDefinition Height="Auto" />
                        </Grid.RowDefinitions>
                        <Image
                            Grid.Row="0"
                            Aspect="AspectFill"
                            Source="{Binding Image}" />
                        <Label
                            Grid.Row="1"
                            Style="{StaticResource PostTitleStyle}"
                            Text="{Binding SubTitle}" />
                        <Label
                            Grid.Row="2"
                            Style="{StaticResource PostDateStyle}"
                            Text="{Binding Date}" />
                        <Label />
                    </Grid>
                </pancakeview:PancakeView>
            </DataTemplate>

How to implement readmore in listview items?

$
0
0

How to implement need readmore and read less inside listview item as it expand and collapse content respectively?

how to preserve Source defined ResourceDictionaries?

Monodevelop failing to create packaged application for GTK#

$
0
0

Hi all,

I've added GTK# to my Xamarin.Forms project and it works pretty well :smile:

But I have problem on Linux (I'm using Debian). Application runs well in debug/release mode, but I have problem when I try to create tar.gz file/package for further distribution - it fails no matter what configuration I take.
I'm using latest stable Monodevelop (7.6.9.22)

Does anyone know what's the catch?


Anyone get gRPC.Core v2.29.0 working with Xamarin.Forms v4.6 on iOS?

$
0
0

I get this error:

Error while loading assemblies: /Users/Arthur/Library/Caches/Xamarin/mtbs/builds/eReader.iOS/0f4caf5560de1374ad8f3c28fd86d686/bin/iPhone/Debug/grpc_csharp_ext.x64.dll e-Reader.iOS

My navigation method, appears to go to somewhere else

$
0
0

Hello community

I have two pages, the fist one is going to be the splash screen, with a .git on it.
Ten I have another screen that with a label and that it.

The way that I go from A to B, is that I create a Timer (To simulate the end of the animation)
the when that animation is finished, I create a new Task to navigate to my other screen

It will navigate, but I do not see my label or anything

And if I remove the create a new task, i get this Android.Util.AndroidRuntimeException: 'Only the original thread that created a view hierarchy can touch its views.'

Why is the rotated image being drawn?

$
0
0

Greetings friends, I am developing an app where the user browses on their device to select an image and this is drawn on a canvas, I am using skiasharp for this, the problem is that I use the app on a Redmi I notice 8 and it works well but I use it on a Galaxy E7 android 5.1 and rotate the image draws it horizontally, I am using images with 90 degree rotation metadata but in the redmi everything is fine I do not understand why this happens in the galaxy E7, I appreciate any help

    `if (libraryBitmap.Height > libraryBitmap.Width)
            {
                canvasView2.HeightRequest = 400;
                canvasView2.WidthRequest = 1000;
            }
            else
            {
                canvasView2.HeightRequest = 300;
                canvasView2.WidthRequest = 1000;
            }
            libraryBitmap_heigth = libraryBitmap.Height;
            libraryBitmap_width = libraryBitmap.Width;
            float left = 0;
            float top = 0;
            float right = info.Width;
            float bottom = info.Height;
            SKRect rect = new SKRect(left, top, right, bottom);
            App.ScreenHeight = info.Height;
            App.ScreenWidth = info.Width;

            canvas.DrawBitmap(libraryBitmap, rect);`

TapGestureRecognizer is not working for ScrollView And CollectionView

$
0
0

I am facing an issue with TapGestureRecognizer, I tried various solution for it but nothing worked. I am sharing my code snippets.

If I comment the scroll view it is working fine but for refresh view we need scroll view and when I uncomment this scrollview code, tapgesture stopped working.

        <StackLayout Padding="0" Margin="20,20,20,20" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
                <RefreshView IsRefreshing="{Binding IsBusy, Mode=OneWay}" Command="{Binding RefreshCleaningListCommand}">
                    <!--<ScrollView InputTransparent="True" VerticalScrollBarVisibility="Never" Orientation="Vertical">-->
                        <StackLayout BindableLayout.ItemsSource="{Binding CleaningList}">
                            <BindableLayout.ItemTemplate>
                                <DataTemplate>
                                    <StackLayout Margin="0, 0, 0, 15">
                                        <Frame 
                                                HorizontalOptions="StartAndExpand" 
                                                VerticalOptions="StartAndExpand"
                                                Padding="10,20,0,10" 
                                                HasShadow="False"
                                                IsClippedToBounds="True" BackgroundColor="#ffffff" CornerRadius="15" >
                                            <views:CleaningListDataTemplate></views:CleaningListDataTemplate>
                                        </Frame>
                                    </StackLayout>
                                </DataTemplate>
                            </BindableLayout.ItemTemplate>
                        </StackLayout>
                    <!--</ScrollView>-->
                </RefreshView>
                <StackLayout.GestureRecognizers>
                    <TapGestureRecognizer NumberOfTapsRequired="1" Command="{Binding HideCalendarViewCommand}"/>
                </StackLayout.GestureRecognizers>
            </StackLayout>

Also If I use collection view, inside refresh view then also Tap gesture is not working It is not working with collection view.

    <StackLayout Padding="0" Margin="20,20,20,20" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
                <RefreshView IsRefreshing="{Binding IsBusy, Mode=OneWay}" Command="{Binding RefreshCleaningListCommand}">
                    <CollectionView ItemsSource="{Binding CleaningList}">
                        <CollectionView.ItemTemplate>
                            <DataTemplate>
                                <StackLayout Margin="0, 0, 0, 15">
                                    <Frame 
                                            HorizontalOptions="StartAndExpand" 
                                            VerticalOptions="StartAndExpand"
                                            Padding="10,20,0,10" 
                                            HasShadow="False"
                                            IsClippedToBounds="True" BackgroundColor="#ffffff" CornerRadius="15" >
                                        <views:CleaningListDataTemplate></views:CleaningListDataTemplate>
                                    </Frame>
                                </StackLayout>
                            </DataTemplate>
                        </CollectionView.ItemTemplate>
                    </CollectionView>
                </RefreshView>
                <StackLayout.GestureRecognizers>
                    <TapGestureRecognizer NumberOfTapsRequired="1" Command="{Binding HideCalendarViewCommand}"/>
                </StackLayout.GestureRecognizers>
            </StackLayout>

Every suggestion will be appreciated.

PhoneDialer adds 835 in front of number.

$
0
0

I am using PhoneDialer with xamarin essential. I found 835 concatenated before phone numbers only on some devices. Some samsung users figured this out and I saw this on AOSP Android 10 based Lineage OS as well.

Viewing all 89864 articles
Browse latest View live