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

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 avoid title view from getting shifted from the center when back button is shown on android

$
0
0

Currently, I am building an app that should run both on iOS and android. I have an image as the title view on the navigation bar which has been set to entered. When we run the app, the title view gets shifted when the back button is shown on android. But on iOS, the title view remains centered even if back button is shown. Is there anyway to keep the title view fixed at the center of the navigation bar both for iOS and android even when back button is shown.

Binding to TabbedPage tabs titles

$
0
0

I have a TabbedPage with two tabs. One tab is for read and the other tab is for unread messages. Titles of tabs should be bound to the count of messages. Both pages have a refresh button and when the button is clicked I want update both tabs title values.

I've tried to implement this by assigning the TabbedPage BindingContext to the CurrentPage BindingContext in the TabbedPage code behind and I bind the Titles of tabs as shown in the example:

<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:local="clr-namespace:TabbedPageWithNavigationPage;assembly=TabbedPageWithNavigationPage"
            x:Class="TabbedPageWithNavigationPage.MainPage">
    <local:ReadMessages Title="{Binding Message.ReadMessagesCount}" />
    <local:UndreadMessages Title="{Binding Message.UnreadMessagesCount}" />       
</TabbedPage>

The issue is when the refresh button is clicked, it updates the property that both titles are bound to, but only the title of the page that I'm currently in actually changes. For example, if I'm in ReadMessages and I hit the refresh button, only the ReadMessages tab's title is updated. It seems like it binds only to the active page.

How can I solve this issue?

Xamarin.forms with visual studio 2017

$
0
0

Can I connect my xamarin apps with azure sql database using rest api or something else? I looking it for my login and register system. Any tutorial with that?

UIScrollCustomRenderer with Transparent Navigation Page Bug

$
0
0

Hey,

At the moment I have the problem that the UIRefreshControl of a Transparent Nav Bar is hidden behind the Notch.

With the ScrollView I set the property "ContentInsetAdjustmentBehavior" to Never, so that content appears behind the Nav Bar.

If I now want to reload the list and I pull down the ScrollView, the UIRefreshControl is not displayed correctly.

Can I give the UIRefreshControl a margin so that the indicator becomes visible?

Screenshot: "us.v-cdn.net/5019960/uploads/editor/1z/exi5kq6lphow.png"

Simple Animation flickers jerky on Android with Cam in Background

$
0
0

Hi guys,

Im using a simple Animation like this:

        lineAnimation = new Animation();
        GoDownAnimation = new Animation(v => image.TranslationY = v, 0, 150, Easing.CubicOut);
        GoUpAnimation = new Animation(v => image.TranslationY = v, 150, 0, Easing.CubicOut);
        lineAnimation.Add(0, 0.5, GoDownAnimation);
        lineAnimation.Add(0.5, 1, GoUpAnimation);

        lineAnimation.Commit(this, "LineAnimation", 16, 1500, null, (v, c) => { image.TranslationY = 0; }, () => true);

This image is above a camera view and going up und down. No problem on iOS, very smoothy, but on Android it flickers jerky (ruckelt)
Without the camera view it is ok on Android, any idea how to solve this?
Im testing with an Android 5.1 and 8.0 smartphone, both the same...

Thank you and best regards
Chris

Issues accessibility Xamarin forms Gesture recognizer - External Keyboard - Android

$
0
0

I could see that the tap gesture recognizer added to an element is not accessible(Talkback) through keyboard on android. Trying to do accessibility test using external keyboard and do a click (alt + enter) on the element having tap gesture recognizer work, it doesn't work.

Checked with sample app from Xamarin Forms, it won't work there also.

Please help me with pointer on making the tap gesture recognizers / links in a Xamarin forms app work in Android ( it works in iOS).

How to design a Knob control in xammarin forms

$
0
0

HIi community...
how to design a knob control for increasing or decreasing the values without skia sharp

if any sample it is helpful for me
Thanks in advance


How to add path to Webview

$
0
0

Hi,

I want to add a manual to my application. The manual is written in HTML5. As I see I only have the possiblility to add the content by using WebView.

I already checked: https://docs.microsoft.com/de-de/xamarin/xamarin-forms/user-interface/webview?tabs=windows#Local_HTML_Content

and I am able to add a webpage with:

var browser = new WebView
{
  Source = "http://xamarin.com"
};

and a Html string with:

var browser = new WebView();
var htmlSource = new HtmlWebViewSource();
htmlSource.Html = @"<html><body>
  <h1>Xamarin.Forms</h1>
  <p>Welcome to WebView.</p>
  </body></html>";
browser.Source = htmlSource;

But what I really want, is to set a path to my HTML file. How can I set this path? I could not find any working example and the description in the documentation does not work for me.

I already tried:

var browser = new WebView();
var htmlSource = new HtmlWebViewSource();
htmlSource.BaseUrl = "file:///./Manual/";
browser.Source = htmlSource;

Can somebody please help me?

Infinite Flow List View

$
0
0

How can I add infinite to the flow list view? Is there an example?

Cannot open pdf document in Pdf viewer

$
0
0

Hi

i am currently trying to open a web pdf in xamarin forms page using following code

Device.OpenUri(new Uri(strWebUrl));

When i click , some pdf's are showing option as "Open with Drive PDF Viewer" . But some pdf's are showing only options of Chrome and IE

Please advice me on this

regards,
Vinay

Xamarin Forms MasterDetail Navigation Page Customizable

$
0
0

I have Created MasterDetail Navigation with Name and icon, I want that when click in icon so open AddDetail Page and when click in Name So open list page.

How to give gesturedetector for circle ?

$
0
0

Hii community
i need a solution or suggestion for Increase or decrease the values of circle like slider

How to do..
if any please suggest
thanks

GC_MINOR: (Nursery full) -> Only on Galaxy S9 Plus of my friend

$
0
0

Hi to everyone,

a few days ago I installed my app on my friend's Samsung Galaxy S9 Plus.
Only on this device, the app is slow.
I think it's an absurd thing, considering that it is the last device released by the Samsung company.

I try to explain what happens, considering that in my app you can download multimedia content (2mb/5mb of files).

The problem appears when, after opening the page where it is possible to search and download the files (a list containing two icons and one label per line appears) I'm pressing the icon to start the download of file.
At that moment, the UI of the app freeze while all other Tasks continue to go (eg Task of download be able to download and save the file without problems).

I immediately thought that the problem was caused by too much work on the main thread (maybe caused by an animation that start as soon as the download starts). [Only on Galaxy S9 Plus of my friend?!]

I also tested the app on the Galaxy S9 Plus, available on browserstack.com, and on their devices, the application works perfectly without problems (even fast).
My friend's phone is fast and it's new (no root or similar).

I'll give you some examples with some images.

Steps:
1. List of files (icon on left, file name, icon on right. This list use FastCells)
2. Click on download (appear a new absolute layout with numer of downloads and progress bar, appear with an animation from bottom to top)
3. If you click on download info layout or swipe download info layout appear a list of separate progress for each file)

These animations work on all devices (Android and iOS), except on the Galaxy S9 Plus of my friend.

To manage the global percentage of downloads, I created an event (DownloadProgressChanged).

I show you some code.
Download method inside Android Service (called by DependencyService.Get().DownloadFile)

private void DownloadFile(string fileName, string url, string source, string id, string uniqueId)
{
    if (NetworkState == NetworkState.ConnectedData || NetworkState == NetworkState.ConnectedWifi)
    {
        // Used inside list of current downloads
        var downloadInfo = new DownloadInfo
        {
            FileName = fileName,
            Progress = 0,
            IsWriting = false, // used to show infinite progress or percentage progress
            UniqueId = uniqueId,
            DownloadStatus = DownloadStatus.Idle // waiting (infinite progress)
        };
        // Add to singleton public list of not exist
        if (!DownloadHandlers.Instance.AtomicCheck(uniqueId))
        {
            DownloadHandlers.Instance.AtomicAdd(downloadInfo);
        }
        else
        {
            downloadInfo = DownloadHandlers.Instance.CurrentDownloadsInfo.First(u => u.UniqueId == uniqueId);
        }
        // Invoke DownloadProgressEvent
        InvokeDownloadProgress();
        try
        {
            var handler = new NativeMessageHandler();
            var httpClient = new HttpClient(handler);
            handler.DisableCaching = true;

            // Change value of IsWriting field
            if (DownloadHandlers.Instance.AtomicCheck(uniqueId))
            {
                DownloadHandlers.Instance.AtomicWriting(uniqueId, true);
            }

            var webApiWrapper = new WebApiWrapper();
            Uri uri = new Uri(url);
            var credentials = XXXXXXXXXXXXXXXXXXXXXXX;
            httpClient = webApiWrapper.ExternalApiRequest(credentials?.access_token);

            // Only response header, because we download the file only after that the stream is ready to write file on disk
            using (var response = httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead).Result)
            {
                var filePath = string.Empty;
                // If file not exist, write file to disk
                if (string.IsNullOrEmpty(fileName)) fileName = "Unknown_" + Guid.NewGuid().ToString("N") + ".xxx";
                fileName = Utils.Normalize(WebUtility.HtmlDecode(fileName), true);

                // Get full path where to save file
                if (!DependencyService.Get<IFilesHandler>().GetFilePath(fileName, out filePath))
                {
                    // Based on exception, throw error or retry if 401 unauthorize (with new token)
                    if (!response.IsSuccessStatusCode)
                    {
                        // Check error code and choose what to do
                        _webApiWrapper.HandleWebException(response, () =>
                        {
                            DownloadFile(fileName, url, source, id, uniqueId);
                        }, out ErrorResponse error);

                        if (error != null)
                        {
                            throw new ApiException("Unable to download file", error.Code);
                        }
                        return;
                    }

                    // Open stream to write file
                    using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                    {
                        var copyTask = response.Content.CopyToAsync(stream);
                        // TOP ahah
                        var length = response.Content.Headers.ContentLength ?? 15000;
                        while (!copyTask.IsCompleted && !copyTask.IsFaulted && !copyTask.IsCanceled)
                        {
                            // While we receive file data, we calculate the percentage
                            var progress = (double)stream.Position / length;
                            Device.BeginInvokeOnMainThread(() =>
                            {
                                // Set single percentage for current download list
                                if (DownloadHandlers.Instance.AtomicCheck(uniqueId))
                                    DownloadHandlers.Instance.AtomicProgress(uniqueId, progress);

                                // Set status of current download
                                downloadInfo.DownloadStatus = DownloadStatus.Downloading;

                                // Invoke DownloadProgressEvent
                                InvokeDownloadProgress();
                            });

                            Thread.Sleep(100);
                        }
                        // Close stream and Delete file if CopyTask fail
                        if (stream.Length == 0 || copyTask.IsFaulted || copyTask.IsCanceled)
                        {
                            downloadInfo.IsWriting = false;
                            stream.Close();
                            if(File.Exists(filePath)) File.Delete(filePath);
                            throw new Exception("Download Error.");
                        }
                        // Max percentage
                        downloadInfo.Progress = 1d;
                        // Save other data
                        DependencyService.Get<IFilesHandler>().WriteInfoJson(fileName, source, id, uniqueId);
                    }
                }
                else
                {
                    response?.Dispose();
                    AlertError("WarningAlertTitle".Translate(), "FileAlreadyExist".Translate(), "OkButton".Translate());
                }
            }

            // Change value of IsWriting and Status field
            if (DownloadHandlers.Instance.AtomicCheck(uniqueId))
            {
                DownloadHandlers.Instance.AtomicWriting(uniqueId, false);
                DownloadHandlers.Instance.AtomicStatus(uniqueId, DownloadStatus.Done);
            }

            // Download finished
            // Decrease number of current downloads
            Console.WriteLine("INFO: Perfect Download.");
            if (_downloadNumber > 0) _downloadNumber--;
            if (_downloadNumber == 0) _isDownload = false;

            // Invoke DownloadProgressEvent
            InvokeDownloadProgress();
        }
        catch (Exception ex)
        {
            .............
        }
    }
    else
    {
        // No internet connection
    }
}

InvokeDownloadProgress method

private void InvokeDownloadProgress()
{
    // Calculate total progress
    var progress = DownloadHandlers.Instance.TotalProgress();
    // Invoke with EventArgs
    DownloadProgressChanged?.Invoke(null, new DownloadProgressChangedEventArgs
    {
        DownloadNumber = _downloadNumber,
        TotalProgress = progress
    });
}

On form side, page code (OnAppearing)

DependencyService.Get<IServerTasks>().DownloadProgressChanged += DownloadProgressChanged;

where DownloadProgressChanged method

private int _downloadNumber = -1;

private void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    var downloadNumber = e.DownloadNumber;
    // Invoke main thread async for animation
    Device.BeginInvokeOnMainThread(async () =>
    {
        // Check current downloads
        if (Math.Abs(e.TotalProgress) < 0.0000001 || downloadNumber == 0)
        {
            progressBar.Progress = 0;
            return;
        }

        // Update progress bar value
        progressBar.Progress = e.TotalProgress / downloadNumber;

        // If there is at least one download, change value of label inside download info layout
        if (downloadNumber > 0 && _downloadNumber != downloadNumber)
        {
            _downloadNumber = downloadNumber;
            lbInfoDownload.Text = string.Format("MultipleDownloadInfoText".Translate(), downloadNumber);

            // If download info layout is not visible
            if (!infoDetailedView.IsVisible)
            {
                // Animate layout from bottom to top
                infoDetailedView.TranslationY = infoDetailedView.Height;
                infoDetailedView.IsVisible = true;
                await infoDetailedView.TranslateTo(0, infoDetailedView.Height - iosRow.Height.Value, 350, Easing.Linear);
            }

            // Change margin of List, so that by scrolling we can see all the elements hidden by download info layout
            layoutList.Margin = new Thickness(0, 0, 0, iosRow.Height.Value);
        }
    });
}

There are other methods used to animate the download info layout (touch and swipe) but it is not necessary to show them because the UI freeze before displaying this layout.

Prevent webview from loosing focus on iOS

$
0
0

I'm trying to create an editor using Xamarin Forms.
The editor is a webview with content editable and a toolbar below.

The way i'm doing it with the following structure:

Grid with two rows
-->WebView [Row 1]
-->ScrollView with horizontal Scroll [Row 2]
---->Stacklayout (with editor actions)
---------> Pick Photo
---------> Bold
---------> Underline
---------> ...

It works well on Android, when i tap on the buttons, it executes the javascript on the webview,the keyboard remains open and the webview doesn't loose focus.

On iOS the webview looses focus and the keyboard closes.
Like this:

https://drive.google.com/file/d/1gO2AdLUy2VYTVNyhAaypaGGQ2mT6RcJ5/view?usp=sharing

Any idea on how can i solve this ?


Error Java.Lang.OutOfMemoryError: Failed to allocate a 132710412 byte allocation with 1048576

$
0
0

Hi everyone, I've been working in my solution in shared project, and I´ve this error when I run my solution on a Samsung Galaxy S6 and S5 only, I'm testing my app and my solution on emulators of differents devices (Galaxy S3, LG G2, Nexus 5, Nexus 4, and google galaxy nexus) all of them in resolutions of 720x1280, 1080x1920, and with android version between 4.0 and 6.1, and all of them run without problem just with Galaxy S5 and S6 . I've seen that the problem is about of the use of large images... but all the image that I use in my forms are in xaml like backgrounds and with the hightest resolution of 648x1152..

This is the error message:

** End of managed Java.Lang.OutOfMemoryError stack trace ---
java.lang.OutOfMemoryError: Failed to allocate a 132710412 byte allocation with 1048576 free bytes and 95MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:609)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)
at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:467)
at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:497)
at android.graphics.drawable.BitmapDrawable.updateStateFromTypedArray(BitmapDrawable.java:762)
at android.graphics.drawable.BitmapDrawable.inflate(BitmapDrawable.java:724)
at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:1215)
at android.graphics.drawable.LayerDrawable.inflateLayers(LayerDrawable.java:254)
at android.graphics.drawable.LayerDrawable.inflate(LayerDrawable.java:164)
at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:1215)
at android.graphics.drawable.Drawable.createFromXml(Drawable.java:1124)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:2630)
at android.content.res.Resources.loadDrawable(Resources.java:2540)
at android.content.res.Resources.getDrawable(Resources.java:806)
at android.content.Context.getDrawable(Context.java:458)
at com.android.internal.policy.PhoneWindow.generateLayout(PhoneWindow.java:3934)
at com.android.internal.policy.PhoneWindow.installDecor(PhoneWindow.java:3981)
at com.android.internal.policy.PhoneWindow.getDecorView(PhoneWindow.java:1969)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3160)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2481)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
**
I'm a kind of confuse of why show this error only in that kind of divices..

Async void behave different on uwp/android

$
0
0

Hi ,

I have this method that I call to bring me the index of an element inside picker .
this works fine on UWP but on android , sometimes it returns the value and sometimes not ..is this is because of "async" couldn't undersatnd the problem here , since , it works 1/5 times on android and just run fine on uwp?

private async void Initlocation()
        {

            DataService d = new DataService();
            var locationss = await d.GetLocatiosn();

            for (int x = 0; x < locationss.Locations.Count(); x++)
            {
                if (locationss.Locations[x].LocationID == Settings.DefaultLocation)
                {
                    PickMe.SelectedIndex = x;
                    break;
                }
            }
        }

Update language translation on the fly using TranslateExtension

$
0
0

Following this guide I'm trying to localize my app. I don't want to get system language. I have 3 resx files for the 3 languages that I want to support. I'm able to set the current culture at start and the strings are displayed correctly.

My goal is to change the language while you are using the app. TranslateExtension class is in MyApp.Resources PCL library and this is my page to select the language.

    <?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:vm="clr-namespace:MyApp"
                 xmlns:t="clr-namespace:MyApp.Resources;assembly=MyApp.Resources"
                 x:Class="MyApp.Pages.LanguagePage"
                 BindingContext="{Binding Source={x:Static vm:App.Locator}, Path=Language}">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <ListView x:Name="contactsListView" Grid.Row="0" ItemsSource="{Binding Languages}" SelectedItem="{Binding SelectedLanguage}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextCell Text="{Binding Value}" Detail="{Binding Key}"  />
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
            <Button Grid.Row="1" Text="{t:Translate Accept}" Clicked="OkButtonClicked" Command="{Binding SaveLanguageCommand}"/>
        </Grid>
    </ContentPage>

When a item in the ListView is selected the accept button should change the text (this is what I want). How can I do that?

Master-Detail Page as a Navigation drawer?

$
0
0

I need a side navigation drawer in the application, the functionality provided by the Master-Detail Page is not compatible with my needs,
I need to have the drawer in the MainPage only and to behave like a NavigationPage: when any item in the master page is clicked, then replacing the hamburger button with a back button that navigate to the previous page.. is it possible with the Xamarin's Master-Detail page?

Xamarin.Forms 4.0 Release Date ?

$
0
0

Hello,

Have you a date for the release or an estimatimate ?

Thanks

Viewing all 89864 articles
Browse latest View live