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

Xamarin Forms - Android Lollipop java.lang.OutOfMemoryError problem

$
0
0

Hello,

When releasing my app in some Lollipop Devices I got some issues with OutOfMemoryError.

The error always happen in ListViews with images. In this case also CircleImages.

The error is:

java.lang.OutOfMemoryError: Failed to allocate a 18662412 byte allocation with 1643192 free bytes and 1604KB until OOM
    at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
    at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
    at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:741)
    at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:562)
    at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:590)
    at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:620)

I have already research and tried a lot of solution but none succeed.

Solutions that I tried so far:

1 - From this topic, I tried to call GC.Collector(1) always when an image is compiled. I add a custom renderer like this:

[assembly: ExportRenderer(typeof(Image), typeof(ImageFixRenderer))]   

public class ImageFixRenderer : ImageRenderer
{
    public ImageFixRenderer()
    {
    }

    protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
    {
        base.OnElementChanged(e);
        GC.Collect(1);
    }

    protected override void Dispose (bool disposing)
    {
        try 
        {
            base.Dispose(disposing);
            GC.Collect(1);
        } 
        catch (Exception ex) 
        {
            System.Diagnostics.Debug.WriteLine(ex.ToString ());
        }
    }
}

But it did not worked.

2 - From this topic , I tried to increase my Java Max Heap Size in Android Options, Advanced Tab to 1G.

But it did not worked also.

3 - From this topic, I tried to add android:largeHeap="true" in manifest file.

But not worked too.

Here is my custom CircleImageRender:

public class CircleImageRenderer : ImageFixRenderer
    {
        /// <summary>
        /// Used for registration with dependency service
        /// </summary>
        public static void Init() { }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
        {
            base.OnElementChanged(e);
            //GC.Collect(1);
            if (e.OldElement == null)
            {

                //Only enable hardware accelleration on lollipop
                if ((int)Android.OS.Build.VERSION.SdkInt < 21)
                {
                    SetLayerType(LayerType.Software, null);
                }

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="canvas"></param>
        /// <param name="child"></param>
        /// <param name="drawingTime"></param>
        /// <returns></returns>
        protected override bool DrawChild(Canvas canvas, global::Android.Views.View child, long drawingTime)
        {
            try
            {
                var radius = Math.Min(Width, Height) / 2;
                var strokeWidth = 10;
                radius -= strokeWidth / 2;


                Path path = new Path();
                path.AddCircle(Width / 2, Height / 2, radius, Path.Direction.Ccw);
                canvas.Save();
                canvas.ClipPath(path);

                var result = base.DrawChild(canvas, child, drawingTime);

                canvas.Restore();

                path = new Path();
                path.AddCircle(Width / 2, Height / 2, radius, Path.Direction.Ccw);

                var paint = new Paint();
                paint.AntiAlias = true;
                paint.StrokeWidth = ((CircleImage)Element).BorderThickness;
                paint.SetStyle(Paint.Style.Stroke);
                paint.Color = ((CircleImage)Element).BorderColor.ToAndroid();

                canvas.DrawPath(path, paint);

                paint.Dispose();
                path.Dispose();
                return result;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Unable to create circle image: " + ex);
            }

            return base.DrawChild(canvas, child, drawingTime);
        }
    }

Please I really need help on this. Anyone can give a hint?


Master Detail Page- keyboard issue.

$
0
0

I am using Menu in master detail page.
I am giving input to the entry, so that the keyboard appears. If I click the menu(on the top for Android & iOS, in the end for windows) button without clicking on detail page, the menu list appearing ,but the keyboard will not dismissing.

It is happening in all the three platforms. How to solve this.

VS 2017 xamarin sample - Hello, Android Multiscreen: Quickstart.

$
0
0

I am attempting to create the first Xamarin form. Using the sample HELLO, ANDROID MULTISSCREEN; QUICKSTART. I am at ADDING A LIST. Instruction Next, create an empty list that can be filled with phone numbers. The MainActivity class will look like this.
[Activity(Label = "Phoneword", MainLauncher = true)]
public class MainActivity : Activity
{
static readonly List phoneNumbers = new List();
...// OnCreate, etc.
}

Their is a copy sign but, there is not instruction as where to copy and place this code. All other code have instruction as where to paste the code. Please help.

Binding From list to labels and buttons from list

$
0
0

Hi , Im binding from my ViewModel to my view a list , but the client requested specific design , can I instead of binding to a list , bind data to labels and buttons that i have created by my self ! see picture to understand more what i mean .
thanks


How to pass Background Image from MainPage to object page from List View

$
0
0

Hello developers !

I'm begginer in xamarin and also in any programming language :wink: I'm just wondering how can i pass a background image to be displayed dependent on string i will pass from my list view where i displaying list of object , i'm storing in each object different background image as a string . I want to unify this becouse for purpose of my project i want to refer to just one page insted of 14. My goal is to have list of items and after clicking specific one , user moves to new page where see background image and text which is bind to object from model.
I tried to add this throught binding on Background Image property in my page.xaml code like but it's not working. :disappointed: :tired_face:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="PersonApp.Views.PersonDetailPage"
             BackgroundImage="{x:Binding Person.Image}">

I don't know how to move on from this becouse at time when i'm writing i cannot figure it out how to pass parameter background image on new page :(

Do you have some tutorial i'm missing to do so ?
How should i pass Background image as binable parameter , should create this var as ImageSource type ?

Progress Bar only works if i use a Delay

$
0
0

Good Day

i am a Loading Page functionality that is defined here https://github.com/UdaraAlwis/Xamarin-Playground/tree/master/XFLoadingPageService . The loading Diaolog only show if i use

await Task.Delay(2000);

my code looks like this

 private async void btnstart_Clicked(object sender, EventArgs e)
        {
            DependencyService.Get<ILodingPageService>().InitLoadingPage(new LoadingIndicatorPage2());
            DependencyService.Get<ILodingPageService>().ShowLoadingPage();

            data .data obj = new data .data ();
            try
            {
                lblstatus.Text = "Before the call";
                // just to showcase a delay...
               // await Task.Delay(2000);

                    var lstentities = await obj.FindPerson_Report_Basic("81248877");

                lblstatus.Text = "After the call";
            }
            catch (Exception ex)
            {
                await DisplayAlert("Error:", ex.Message, "Ok");
            }
            finally
            {
                obj = null;
                DependencyService.Get<ILodingPageService>().HideLoadingPage();
            }
        }

but the loading page does not load , as you can see i commented the Delay part.

Thanks

Xamarin.Forms CardsView nuget package

$
0
0

Hi all) I've released new package for Xamarin.Forms (Something like Tinder's CardsView)
Maybe, someone will be interested in it

nuget.org/packages/CardsView/ -- nuget
github.com/AndreiMisiukevich/CardView -- source and samples

CarouselView implementation, CardsView nuget package


ListView not working in CarouselView

$
0
0

Greetings!

I am trying to include a ListView as an element in a static array in a CarouselView. This is the XAML code in my sandbox project:

<?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:local="clr-namespace:XamarinSandbox"
             xmlns:cv="clr-namespace:CarouselView.FormsPlugin.Abstractions;assembly=CarouselView.FormsPlugin.Abstractions"
             x:Class="XamarinSandbox.MainPage">

    <cv:CarouselViewControl x:Name="carousel" 
                            InterPageSpacing="10"
                            Orientation="Horizontal"
                            Position="{Binding Position}"
                            ShowArrows="True"
                            ShowIndicators="True"
                            HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">

        <cv:CarouselViewControl.ItemsSource>
            <x:Array Type="{x:Type View}">

                <Label Text="{Binding LabelText}" BackgroundColor="CadetBlue" FontSize="Large"
                       HorizontalTextAlignment="Center" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center" VerticalOptions="CenterAndExpand" />

                <StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
                    <Label Text="{Binding ProgramModeInstructionsText}" FontSize="Large"
                           HorizontalTextAlignment="Center" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center" VerticalOptions="CenterAndExpand" />

                    <ListView ItemsSource="{Binding ItemsSource}" SelectedItem="{Binding SelectedItem}"
                              HasUnevenRows="True" HeightRequest="200" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                               <TextCell Text="REMOVE THIS LINE AND THE CODE COMPILES" />
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>

                    <Label Text="{Binding SelectedProgramModeDescription}" FontSize="Large"
                           HorizontalTextAlignment="Center" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center" VerticalOptions="CenterAndExpand" />
                </StackLayout>

            </x:Array>
        </cv:CarouselViewControl.ItemsSource>

    </cv:CarouselViewControl>

</ContentPage>

With this XAML definition, I receive the following compilation error: Value cannot be null. Parameter name: fieldType
(I am using [assembly: XamlCompilation(XamlCompilationOptions.Compile)])

I have been removing lines and compiling to see where the error lays.
If I remove the TextCell element, then the XAML definition compiles without error.

I am at a loss to understand what is going on. This is a basic sandbox project with nothing else in it save the view model that responds to this view. However, I have removed every binding to make the example as simple as possible. The code behind class has had no code added to it.

Does anyone have any ideas why this is not compiling?
Using Xamarin version 2.5.0.280555.
Thank you.

Xamarin.CardIO documentation or examples.

$
0
0

Hello. A want scan debit/credit card data (card number, holder name etc.) using smartphone camera. I found Xamarin.CardIO.iOS and Xamarin.CardIO.Android libraries, but there are no any documentation or examples how to use it. In the end I want to create some Xamarin Forms control for using it from XAML. But now I need any documentation or examples. Could someone help me?

MVVM cascading pickers SelectedItem not firing

$
0
0

Hi. I have two pickers that I want to cascade, i.e., when a user picks a value in the first picker, the second one is populated based on the selected item.

Here's what I have:
XAML:

  <Picker x:Name="C" Title="C" ItemsSource="{Binding Cs}" ItemDisplayBinding="{Binding Value}" SelectedItem="{Binding SelectedC, Mode=TwoWay}" />
  <Picker x:Name="T" Title="T" ItemsSource="{Binding Ts}" SelectedItem="{Binding SelectedT}" />

In View Model class:

public List<KeyValuePair<string, string>> Cs { get; private set; } = new List<KeyValuePair<string, string>>();   // This gets populated in the code behind.

private KeyValuePair<string, string> _SelectedC;
public KeyValuePair<string, string> SelectedC
     {
         get => _SelectedC;
         set
         {
            _SelectedC = value;
             // Update Ts item source.
         }
     }

Problem is SelectedC's setter never fires. Please let me know if you have any ideas. Thanks.

How to get the length in seconds of a WAV file?

$
0
0

Hi guys, I have been trying to find out how to get the length of a wave file recording for both Android and iOS.
Can it be done in the PCL, or there are specific platform methods to get this length?

HotReload LiveReload LiveXaml [Mac] [Windows] [nuget package] [opensource]

BaseViewModel, Command holder, Property holder.. experimental

$
0
0

BaseViewModel

If you don't want to use fody and want to save space/time during development (creating private fields) with avoiding contructions like:

        private string _val;
        public string Val
        {
            get => _val;
            set
            {
                if(value == _val)
                {
                    return;
                }
                _val = value;
                OnPropertyChanged();
            }
        }

        private ICommand _command;
        public ICommand Command => _command ?? (_command = new Command(() =>
        {
            //check if it isn't fast double tap..oh... try/cathc etc..
        }));

You can copy and paste two classes https://github.com/AndreiMisiukevich/BaseViewModel/tree/master/Lib/BaseViewModel
Make you view model to inherit BaseViewModel and simplify code above:

        public string Val
        {
            get => Get<string>();
            set => Set(value);
        }

        public ICommand Command => Cmd() ?? RegCmd(() =>
        {
        }, TimeSpan.FromMilliseconds(300), true, ex => {
            //handle exception if you want
        });
        //first param - actionFrequency
        //second param - shouldSuppressExceptions, will be no crash if exception occurs
        //third param - onExceptionAction, if you want to handle exception after suppressing

Very small sample: https://github.com/AndreiMisiukevich/BaseViewModel/tree/master/BaseViewModel.Sample

Link: https://github.com/AndreiMisiukevich/BaseViewModel

I'm not sure, that it is useful and makes sense at all :) experimental

All properties are stored in dictionary.

How to add swiping dots to Tabbed/Carousel page?

$
0
0

I'm wondering how to add dots indicating to swipe screens in either TabbedPage or CarouselPage like in the below image?

I tried adding images for that but they don't look natural so is there a real way for doing that?

My above workaround explanation in an example with 3 page:

I create 3 images each image has 3 dots one of them is highlighted:

First image highlighted dot is the first one.

Second image highlighted dot is the second one.

and etc.


Hamburger icon iOS (Xamarin.Forms)

$
0
0

I followed this wonderful blog post and my hamburger menu works great... on Android. The icon appears, and it is even animated.

On iOS I don't get the hamburger. I have put a hamburger icon into the toolbar, but of course it sits in the middle, not where it belongs (on the far left, where the back arrow would otherwise be).

Any ideas on how I can get this icon to work?

Thanks!!

Sample ToDo - Downloaded - How do I execute

$
0
0

I have downloaded the sample ToDo List. There are many members in the folder. What member do I click to execute the sample?

WebView/HybridWebView Context Menu

$
0
0

Is there any way to show the context menu? especially ios.
do you have an idea or sample? can you please share?

Thanks

Unhandled Exception: Xamarin.Forms.Xaml.XamlParseException: Position 12:21. StaticResource not found

$
0
0

I'm trying to implement Rich Text box in xamarin forms. There is this exception occurring.

Unhandled Exception: Xamarin.Forms.Xaml.XamlParseException: Position 12:21. StaticResource not found for key FromRTFConverter occurred

This is my xaml code

    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:local="clr-namespace:demoapp"
                  xmlns:converters="clr-namespace:demoapp"
                 x:Class="demoapp.MainPage"
                >


        <StackLayout Orientation="Vertical">

            <Label Text="Simple xamarin forms control" TextColor="Red" HorizontalOptions="Center" FontSize="Large"/>
            <Entry />
            <StackLayout>

                <Picker x:Name="pickerDynamicData" Title="Select Country" HorizontalOptions="FillAndExpand" SelectedItem="{Binding Name}" SelectedIndexChanged="PickerSelection" HeightRequest="50" TextColor="Blue"/>
                <Editor Text="{Binding CaretNote, Mode=OneWay, Converter={StaticResource FromRTFConverter}}" MinimumWidthRequest="250" HorizontalOptions="Fill" VerticalOptions="StartAndExpand"  IsEnabled="False"/>
            </StackLayout>
        </StackLayout>

    </ContentPage>

I tried to follow this example to solve the issue. So I made this changes in my XAML code

    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:local="clr-namespace:demoapp"
                  xmlns:converters="clr-namespace:demoapp"
                 x:Class="demoapp.MainPage"
                >

        <ContentPage.Resources>
            <ResourceDictionary>
                <converters:FromRTFConverter x:Key="FromRTFConverter" />
            </ResourceDictionary>
        </ContentPage.Resources>
        <StackLayout Orientation="Vertical">

            <Label Text="Simple xamarin forms control" TextColor="Red" HorizontalOptions="Center" FontSize="Large"/>
            <Entry />
            <StackLayout>

                <Picker x:Name="pickerDynamicData" Title="Select Country" HorizontalOptions="FillAndExpand" SelectedItem="{Binding Name}" SelectedIndexChanged="PickerSelection" HeightRequest="50" TextColor="Blue"/>
                <Editor Text="{Binding CaretNote, Mode=OneWay, Converter={StaticResource FromRTFConverter}}" MinimumWidthRequest="250" HorizontalOptions="Fill" VerticalOptions="StartAndExpand"  IsEnabled="False"/>
            </StackLayout>
        </StackLayout>

    </ContentPage>

But I get this exception

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

This is my xaml.cs code

    namespace demoapp
    {
        public partial class MainPage : ContentPage
        {
            public MainPage()
            {
                InitializeComponent();
                ObservableCollection<string> objStringList = new ObservableCollection<string>();

                //Mostly below ObservableCollection Items we will get from server but here Iam mentioned static data.
                ObservableCollection<PickerItems> objClassList = new ObservableCollection<PickerItems>();

                objClassList.Add(new PickerItems { Name = "India" });
                objClassList.Add(new PickerItems { Name = "Pakistan" });


                objClassList.Add(new PickerItems { Name = "America" });
                objClassList.Add(new PickerItems { Name = "London" });

                objClassList.Add(new PickerItems { Name = "China" });

                /*Here we have to assign service Items to one ObservableCollection<string>() for this purpose
                I am using foreach and we can add each item to the ObservableCollection<string>(). */

                foreach (var item in objClassList)
                {
                    // Here I am adding each item Name to the ObservableCollection<string>() and below I will assign to the Picker
                    objStringList.Add(item.Name);
                }

                //Now I am given ItemsSorce to the Pickers
                pickerDynamicData.ItemsSource = objStringList;


            }

            private void PickerSelection(object sender, EventArgs e)
            {
                var picker = (Picker)sender;
                int selectedIndex = picker.SelectedIndex;
                //put your code here
            }

            private void PickerSelection1(object sender, EventArgs e)
            {
                var picker = (Picker)sender;
                int selectedIndex = picker.SelectedIndex;
                //put your code here
            }

        private class StackEntry
        {
            public int NumberOfCharactersToSkip { get; set; }
            public bool Ignorable { get; set; }
            public StackEntry(int numberOfCharactersToSkip, bool ignorable)
            {
                NumberOfCharactersToSkip = numberOfCharactersToSkip;
                Ignorable = ignorable;
            }
        }

        private static readonly Regex _rtfRegex = new Regex(@"\\([a-z]{1,32})(-?\d{1,10})?[ ]?|\\'([0-9a-f]{2})|\\([^a-z])|([{}])|[\r\n]+|(.)", RegexOptions.Singleline | RegexOptions.IgnoreCase);

        /// <summary>
        /// RTF reserved words
        /// </summary>
        private static readonly List<string> destinations = new List<string>
        {
            "aftncn","aftnsep","aftnsepc","annotation","atnauthor","atndate","atnicn","atnid",
            "atnparent","atnref","atntime","atrfend","atrfstart","author","background",
            "bkmkend","bkmkstart","blipuid","buptim","category","colorschememapping",
            "colortbl","comment","company","creatim","datafield","datastore","defchp","defpap",
            "do","doccomm","docvar","dptxbxtext","ebcend","ebcstart","factoidname","falt",
            "fchars","ffdeftext","ffentrymcr","ffexitmcr","ffformat","ffhelptext","ffl",
            "ffname","ffstattext","field","file","filetbl","fldinst","fldrslt","fldtype",
            "fname","fontemb","fontfile","fonttbl","footer","footerf","footerl","footerr",
            "footnote","formfield","ftncn","ftnsep","ftnsepc","g","generator","gridtbl",
            "header","headerf","headerl","headerr","hl","hlfr","hlinkbase","hlloc","hlsrc",
            "hsv","htmltag","info","keycode","keywords","latentstyles","lchars","levelnumbers",
            "leveltext","lfolevel","linkval","list","listlevel","listname","listoverride",
            "listoverridetable","listpicture","liststylename","listtable","listtext",
            "lsdlockedexcept","macc","maccPr","mailmerge","maln","malnScr","manager","margPr",
            "mbar","mbarPr","mbaseJc","mbegChr","mborderBox","mborderBoxPr","mbox","mboxPr",
            "mchr","mcount","mctrlPr","md","mdeg","mdegHide","mden","mdiff","mdPr","me",
            "mendChr","meqArr","meqArrPr","mf","mfName","mfPr","mfunc","mfuncPr","mgroupChr",
            "mgroupChrPr","mgrow","mhideBot","mhideLeft","mhideRight","mhideTop","mhtmltag",
            "mlim","mlimloc","mlimlow","mlimlowPr","mlimupp","mlimuppPr","mm","mmaddfieldname",
            "mmath","mmathPict","mmathPr","mmaxdist","mmc","mmcJc","mmconnectstr",
            "mmconnectstrdata","mmcPr","mmcs","mmdatasource","mmheadersource","mmmailsubject",
            "mmodso","mmodsofilter","mmodsofldmpdata","mmodsomappedname","mmodsoname",
            "mmodsorecipdata","mmodsosort","mmodsosrc","mmodsotable","mmodsoudl",
            "mmodsoudldata","mmodsouniquetag","mmPr","mmquery","mmr","mnary","mnaryPr",
            "mnoBreak","mnum","mobjDist","moMath","moMathPara","moMathParaPr","mopEmu",
            "mphant","mphantPr","mplcHide","mpos","mr","mrad","mradPr","mrPr","msepChr",
            "mshow","mshp","msPre","msPrePr","msSub","msSubPr","msSubSup","msSubSupPr","msSup",
            "msSupPr","mstrikeBLTR","mstrikeH","mstrikeTLBR","mstrikeV","msub","msubHide",
            "msup","msupHide","mtransp","mtype","mvertJc","mvfmf","mvfml","mvtof","mvtol",
            "mzeroAsc","mzeroDesc","mzeroWid","nesttableprops","nextfile","nonesttables",
            "objalias","objclass","objdata","object","objname","objsect","objtime","oldcprops",
            "oldpprops","oldsprops","oldtprops","oleclsid","operator","panose","password",
            "passwordhash","pgp","pgptbl","picprop","pict","pn","pnseclvl","pntext","pntxta",
            "pntxtb","printim","private","propname","protend","protstart","protusertbl","pxe",
            "result","revtbl","revtim","rsidtbl","rxe","shp","shpgrp","shpinst",
            "shppict","shprslt","shptxt","sn","sp","staticval","stylesheet","subject","sv",
            "svb","tc","template","themedata","title","txe","ud","upr","userprops",
            "wgrffmtfilter","windowcaption","writereservation","writereservhash","xe","xform",
            "xmlattrname","xmlattrvalue","xmlclose","xmlname","xmlnstbl",
            "xmlopen"
        };

        /// <summary>
        /// Special characters
        /// </summary>
        private static readonly Dictionary<string, string> specialCharacters = new Dictionary<string, string>
        {
            { "par", "\n" },
            { "sect", "\n\n" },
            { "page", "\n\n" },
            { "line", "\n" },
            { "tab", "\t" },
            { "emdash", "\u2014" },
            { "endash", "\u2013" },
            { "emspace", "\u2003" },
            { "enspace", "\u2002" },
            { "qmspace", "\u2005" },
            { "bullet", "\u2022" },
            { "lquote", "\u2018" },
            { "rquote", "\u2019" },
            { "ldblquote", "\u201C" },
            { "rdblquote", "\u201D" },
        };

        /// <summary>
        /// Strip RTF Tags from RTF Text
        /// </summary>
        /// <param name="inputRtf">RTF formatted text</param>
        /// <returns>Plain text from RTF</returns>
        public static string StripRichTextFormat(string inputRtf)
        {
            if (inputRtf == null)
            {
                return null;
            }

            string returnString;

            var stack = new Stack<StackEntry>();
            bool ignorable = false;              // Whether this group (and all inside it) are "ignorable".
            int ucskip = 1;                      // Number of ASCII characters to skip after a unicode character.
            int curskip = 0;                     // Number of ASCII characters left to skip
            var outList = new List<string>();    // Output buffer.

            MatchCollection matches = _rtfRegex.Matches(inputRtf);

            if (matches.Count > 0)
            {
                foreach (Match match in matches)
                {
                    string word = match.Groups[1].Value;
                    string arg = match.Groups[2].Value;
                    string hex = match.Groups[3].Value;
                    string character = match.Groups[4].Value;
                    string brace = match.Groups[5].Value;
                    string tchar = match.Groups[6].Value;

                    if (!String.IsNullOrEmpty(brace))
                    {
                        curskip = 0;
                        if (brace == "{")
                        {
                            // Push state
                            stack.Push(new StackEntry(ucskip, ignorable));
                        }
                        else if (brace == "}")
                        {
                            // Pop state
                            StackEntry entry = stack.Pop();
                            ucskip = entry.NumberOfCharactersToSkip;
                            ignorable = entry.Ignorable;
                        }
                    }
                    else if (!String.IsNullOrEmpty(character)) // \x (not a letter)
                    {
                        curskip = 0;
                        if (character == "~")
                        {
                            if (!ignorable)
                            {
                                outList.Add("\xA0");
                            }
                        }
                        else if ("{}\\".Contains(character))
                        {
                            if (!ignorable)
                            {
                                outList.Add(character);
                            }
                        }
                        else if (character == "*")
                        {
                            ignorable = true;
                        }
                    }
                    else if (!String.IsNullOrEmpty(word)) // \foo
                    {
                        curskip = 0;
                        if (destinations.Contains(word))
                        {
                            ignorable = true;
                        }
                        else if (ignorable)
                        {
                        }
                        else if (specialCharacters.ContainsKey(word))
                        {
                            outList.Add(specialCharacters[word]);
                        }
                        else if (word == "uc")
                        {
                            ucskip = Int32.Parse(arg);
                        }
                        else if (word == "u")
                        {
                            int c = Int32.Parse(arg);
                            if (c < 0)
                            {
                                c += 0x10000;
                            }
                            outList.Add(Char.ConvertFromUtf32(c));
                            curskip = ucskip;
                        }
                    }
                    else if (!String.IsNullOrEmpty(hex)) // \'xx
                    {
                        if (curskip > 0)
                        {
                            curskip -= 1;
                        }
                        else if (!ignorable)
                        {
                            int c = Int32.Parse(hex, System.Globalization.NumberStyles.HexNumber);
                            outList.Add(Char.ConvertFromUtf32(c));
                        }
                    }
                    else if (!String.IsNullOrEmpty(tchar))
                    {
                        if (curskip > 0)
                        {
                            curskip -= 1;
                        }
                        else if (!ignorable)
                        {
                            outList.Add(tchar);
                        }
                    }
                }
            }
            else
            {
                // Didn't match the regex
                returnString = inputRtf;
            }

            returnString = String.Join(String.Empty, outList.ToArray());

            return returnString;
        }
        public class PickerItems
        {
            public string Name { get; set; }
        }
        }
    }

I don't have any clue how to fix this. Any suggestions?

How to stop vidio playing in WebView

$
0
0

Dear experts,

I work on a Xamarin.Forms app (UWP!). It has a Master-Details architecture. The Master page has a ListView, and each item in it opens a corresponding Detail page. The first Detail page has only a WebView that plays a YouTube video upon loading. The second Detail view has just a placeholder label for now. Where I switch from first Detail page to the second, the sound of the video from the first Detail page is still heard. And when I switch back to the first Detail page, the video loads again, and now I hear two voices. How can I stop the video upon switching to the second Detail page and resume when going back? If this is not possible, how can I just stop the video upon leaving its Detail page?

Here is some code:

In MainMDPage.xaml.cs:

`
private void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var item = e.SelectedItem as MainMDPageMenuItem;
if (item == null)
return;

        var page = (Page)Activator.CreateInstance(item.TargetType);

        Detail = new NavigationPage(page);
        IsPresented = false;

        MasterPage.ListView.SelectedItem = null;

        PreviouslySelectedItem = item;
    }

`

In MainMDPageMaster.xaml.cs:

`
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainMDPageMaster : ContentPage
{
public ListView ListView;

    public MainMDPageMaster()
    {
        InitializeComponent();

        BindingContext = new MainMDPageMasterViewModel();
        ListView = MenuItemsListView;
    }

    class MainMDPageMasterViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<MainMDPageMenuItem> MenuItems { get; set; }

        public MainMDPageMasterViewModel()
        {
            MenuItems = new ObservableCollection<MainMDPageMenuItem>(new[]
            {
                new MainMDPageMenuItem { Id = 0, Title = "Videos", TargetType = typeof(VideoPage), IconSource = @"Assets\film-strip.jpg" },
                new MainMDPageMenuItem { Id = 1, Title = "Products", TargetType = typeof(ProductsPage), IconSource = @"Assets\products.jpg" },
            });
        }

        #region INotifyPropertyChanged Implementation
        public event PropertyChangedEventHandler PropertyChanged;
        void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            if (PropertyChanged == null)
                return;

            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion
    }
}`

Thanks!

Viewing all 91519 articles
Browse latest View live


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