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

Why the iOS build of Xamarin.Forms shows the background color of listviews as white?

$
0
0

Android build of Xamarin.Forms shows the correct color of the list view background. The background of the list view is grey and the text color is white. But in the iOS build the background color gets changed to white and as a result the texts which are also white in color are not visible until an item from the list view is selected. Please help I am new to Xamrin.
Thanks


NullReferenceException on Grid.CalculateAutoCells [Only XF iOS]

$
0
0

Hi,

I'm developing an app with Xamarin Forms from 7 months.
My app worked very well.
I have done 1 month on Android side, because I fixed some bugs and added some features.

Today I have ported these mods on iOS side and now I have a NullReferenceException on Grid, when I scroll the List View. (On Android all works perfectly)

Here's what happens:
- I open the page that contains the list
- The list is loaded and displayed correctly
- If I try to scroll through the list, appears this exception

Stack Trace:

at Xamarin.Forms.Grid.CalculateAutoCells (System.Double width, System.Double height) [0x00357] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\GridCalc.cs:144 at Xamarin.Forms.Grid.MeasureGrid (System.Double width, System.Double height, System.Boolean requestSize) [0x0000c] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\GridCalc.cs:483 at Xamarin.Forms.Grid.LayoutChildren (System.Double x, System.Double y, System.Double width, System.Double height) [0x0000e] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\GridCalc.cs:17 at Xamarin.Forms.Layout.UpdateChildrenLayout () [0x000c7] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\Layout.cs:229 at Xamarin.Forms.Layout.OnSizeAllocated (System.Double width, System.Double height) [0x0000f] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\Layout.cs:194 at Xamarin.Forms.VisualElement.SizeAllocated (System.Double width, System.Double height) [0x00000] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\VisualElement.cs:629 at Xamarin.Forms.Layout+<>c.<OnChildMeasureInvalidated>b__39_0 () [0x00080] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\Layout.cs:332 at Foundation.NSAsyncActionDispatcher.Apply () [0x00000] in /Users/builder/data/lanes/3969/44931ae8/source/xamarin-macios/src/Foundation/NSAction.cs:163 at (wrapper managed-to-native) UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr) at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Users/builder/data/lanes/3969/44931ae8/source/xamarin-macios/src/UIKit/UIApplication.cs:79 at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00038] in /Users/builder/data/lanes/3969/44931ae8/source/xamarin-macios/src/UIKit/UIApplication.cs:63 at MusiDownPortable.iOS.Application.Main (System.String[] args) [0x00008] in /Users/steebono/SourceTree/musidown/MusiDownPortable/MusiDownPortable/MusiDownPortable.iOS/Main.cs:17

Sometimes scroll works but when I try to reload list I have this exception:

Second StackTrace:

at Xamarin.Forms.Grid.GetLastAutoColumn (Xamarin.Forms.BindableObject child) [0x00016] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\GridCalc.cs:657 at Xamarin.Forms.Grid.ExpandLastAutoColumnIfNeeded (System.Double width, System.Boolean expandToRequest) [0x00024] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\GridCalc.cs:331 at Xamarin.Forms.Grid.MeasureGrid (System.Double width, System.Double height, System.Boolean requestSize) [0x0013a] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\GridCalc.cs:520 at Xamarin.Forms.Grid.LayoutChildren (System.Double x, System.Double y, System.Double width, System.Double height) [0x0000e] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\GridCalc.cs:17 at Xamarin.Forms.Layout.UpdateChildrenLayout () [0x000c7] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\Layout.cs:229 at Xamarin.Forms.Layout.OnSizeAllocated (System.Double width, System.Double height) [0x0000f] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\Layout.cs:194 at Xamarin.Forms.VisualElement.SizeAllocated (System.Double width, System.Double height) [0x00000] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\VisualElement.cs:629 at Xamarin.Forms.Layout+<>c.<OnChildMeasureInvalidated>b__39_0 () [0x00080] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\Layout.cs:332 at Foundation.NSAsyncActionDispatcher.Apply () [0x00000] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/Foundation/NSAction.cs:163 at (wrapper managed-to-native) UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr) at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/UIKit/UIApplication.cs:79 at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00038] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/UIKit/UIApplication.cs:63 at MusiDownPortable.iOS.Application.Main (System.String[] args) [0x00008] in /Users/steebono/SourceTree/musidown/MusiDownPortable/MusiDownPortable/MusiDownPortable.iOS/Main.cs:17

XAML Code:

<ListView x:Name="listView" ItemSelected="OnItemSelected" IsVisible="False" HasUnevenRows="False" RowHeight="50" IsPullToRefreshEnabled="True" Refreshing="mySongs_OnRefreshing"> <x:Arguments> <ListViewCachingStrategy>RecycleElement</ListViewCachingStrategy> </x:Arguments> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <ViewCell.ContextActions> <MenuItem Clicked="mySongDelete_OnClicked" CommandParameter="{Binding .}" Text="Delete" IsDestructive="True" /> </ViewCell.ContextActions> <Grid> <Grid.RowDefinitions> <RowDefinition Height="50" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="5" /> <ColumnDefinition Width="35" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="35" /> <ColumnDefinition Width="5" /> </Grid.ColumnDefinitions> <ff:CachedImage Source="{Binding FavoriteIcon}" CacheDuration="1" RetryCount="1" Aspect="AspectFit" HorizontalOptions="StartAndExpand" Grid.Row="0" Grid.Column="1"> <ff:CachedImage.GestureRecognizers> <TapGestureRecognizer Tapped="onClick_Favorite"/> </ff:CachedImage.GestureRecognizers> </ff:CachedImage> <Label Text="{Binding Title}" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center" HorizontalTextAlignment="Center" LineBreakMode="TailTruncation" FontSize="Medium" Grid.Row="0" Grid.Column="2" /> <ff:CachedImage Source="{Binding MenuIcon}" CacheDuration="1" RetryCount="1" Aspect="AspectFit" HorizontalOptions="EndAndExpand" Grid.Row="0" Grid.Column="3"> <ff:CachedImage.GestureRecognizers> <TapGestureRecognizer Tapped="onClick_Menu"/> </ff:CachedImage.GestureRecognizers> </ff:CachedImage> </Grid> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView>

C# Code:

Inside OnAppearing():

`

// Other code here

listView.ItemSource = _myListItems;

// Other code here

`

My List is declared as:

`

private ObservableCollection<MyItemEntry> _myListItems = new ObservableCollection<MyItemEntry>();

`

MyItemEntry object is a class derived from INotifyPropertyChanged

I have an event that load and reload the list if needed:

`

        // Other code here

        // Start async operation
                Task.Run(() =>
                {
                    // Clear List
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        if (_myListItems.Any()) _myListItems.Clear();
                    });
                    // Get refreshed list.
                    var myList = DependencyService.Get<IItemHandler>().ReadItem;

                    if (myList.Any())
                    {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            foreach (var itemDataEntry in myList)
                            {
                var menuIcon = "Menu100.png";
                                var favoriteIcon = itemDataEntry.Favorite ? "Favfill.png" : "Fav100.png";
                                _myListItems.Add(new MyItemEntry
                                {
                                    FavoriteIcon = favoriteIcon,
                                    MenuIcon = menuIcon,
                                    Title = decSong
                                });
                            }
                            if (_mySongsItems.Any())
                            {
                                Device.BeginInvokeOnMainThread(() =>
                                {
                                    listView.IsVisible = true;
                                    loadingIndicator.IsVisible = false;
                                    loadingIndicator.IsRunning = false;
                                    layoutDataInfo.IsVisible = false;
                                    lbDataInfo.IsVisible = false;
                                });
                            }
                            else
                            {
                                Device.BeginInvokeOnMainThread(() =>
                                {
                                    listView.IsVisible = false;
                                    loadingIndicator.IsVisible = false;
                                    loadingIndicator.IsRunning = false;
                                    layoutDataInfo.IsVisible = true;
                                    imgDataInfo.IsVisible = true;
                                    lbDataInfo.IsVisible = true;
                                });
                            }
                        });
                    }
                    else
                    {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            listView.IsVisible = false;
                            loadingIndicator.IsVisible = false;
                            loadingIndicator.IsRunning = false;
                            layoutDataInfo.IsVisible = true;
                            imgDataInfo.IsVisible = true;
                            lbDataInfo.IsVisible = true;
                        });
                    }
                });

// Other code here for update list if needed

`

This codes on Android work perfectly. On iOS this codes work perfectly but if i try to scroll the list, I have that Exception.

A important thing is that this Event do not fire when I scroll the List.
I think that my code is not the cause of this Exception, because this happend only if I scroll
If I open the page and after do nothing, all work perfectly. I do not manage in any way scrolling or similar.

I have viewed the code of Xamarin Libraries and seems That Grid.ColumnDefinitions at some point became null.

First StackTrace say:

at Xamarin.Forms.Grid.CalculateAutoCells (System.Double width, System.Double height) [0x00357] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\GridCalc.cs:144

In this line there is a for cycle:

for (var i = 0; i < _columns.Count; i++)

Second StackTrace say:

at Xamarin.Forms.Grid.CalculateAutoCells (System.Double width, System.Double height) [0x00357] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\GridCalc.cs:657

In this line there is a if with same variable of first stacktrace:
if (_columns[i].Width.IsAuto)

so I think that the null reference exception is caused by _columns var.
As you can see in my xaml code I have set ColumnDefinitions.

This error happens when the list has already been created and displayed so.. someone set this to null at some point or Layout.UpdateChildrenLayout fails to get ColumnDefinitions value?

Another observation is that I set ItemSource of listView inside OnAppearing method; when I reload page, I clear my list object and I re-insert all updated items to list. But I think that this is not a problem because my list's items derived from INotifyPropertyChanged and my list is a ObservableCollecion list.

Xamarin Mac Env: last version iOS: 10.1 Xamarin Forms: 2.3.3.168 / 2.3.3.180 (Tried both)

Sorry for my english.

Thanks,
Stefano

How do i change the path of my .apk(Archive)?

$
0
0

I'm not getting to change path of my .apk file. In current path is not possible(name too big) and i'd like to move to root. How can i do?

Application.Resources StaticResource not found for key

$
0
0

Hi,

I am trying to define a Style for a custom control I have created in the Application.Resources section of my App.xaml.cs file. However the page that references this file raises an exception (StaticResource not found for key).

The sample here :-

https://github.com/xamarin/xamarin-forms-samples

Doesn't use a Key or a Custom Control for it's Application.Resources so I am not exactly sure how to get this working.

Is there any more comprehensive examples available or any pointers as to how to get this working?

Update: The same Style defined in the Page's Resources section, works successfully.

Thanks

Paul Diston

Android service close if app closes

$
0
0

hi guys i'm trying to do an android service for my app and i'm facing this issue, i've been looking for information about it and found that i need to use StartCommandResult.Sticky option for the service to not get closed, but it is not working here's the piece of code i'm using:

    protected override StartCommandResult onStartCommand(Intent intent, StartCommandFlags flags, int startId){
        var t = new Task(() => {

            DoServiceWork();
        });

        t.Start();

        return StartCommandResult.Sticky;
    }

and this is how i've been calling it in my activity

protected override void OnCreate(Bundle bundle){
    new Task(StartService).Start();
}

void StartService(){
    var intent = new Intent(Application.Context, typeof(MyService));
    Application.Context.StartService(intent);
}

but didin't work =(
can anyone help me, for you guys to know i've been trying things the whole day believe me

How to register background service for IOS in xamarin.Forms?

$
0
0

I need to push my data to server after every time interval using background service ,either app is in background or closed.

Editor not showing keyboard in Android

$
0
0

Hi,

I'm having a strange issue in my Forms application regarding an Editor element. There is one Editor field that doesn't show the soft keyboard when it's selected.

For some reason if I programmatically focus it using .Focus() then the keyboard appears without any issue.

This problem is only on Android - the iOS version works fine. Just wondering if anyone else has seen this.

Kind regards
Jeremy

Which is the proper way of validations of forms?

$
0
0

I have registration form. There are fields like Email, password etc. How to implement validations?
On submit of form, required validations & textbox should be highlighted.


Buy Cheapest Android & Ios App Installs

$
0
0

STEAMSEO is a self-service mobile advertising platform that creates, manages and measures mobile ad campaigns by using a genius artificial intelligence and machine learning.

It uses CPI system which is the most efficient and cost-effective bidding system for mobile apps since it doesn’t make any other expenses than installs.

Also, it is so easy to use, you’ll only manage with one single dashboard and track all the important metrics and the information flows from there.
The platform operates on a CPI, CPA, CPE, CPV, CPC and CPM bidding basis, which allows advertisers to stay in full control of their campaigns and optimize ad spend to best reach their target audience.

You can choose below mentioned services

IOS App Installs
Android Installs
High Retention Installs
Keyword Installs
Country (GEO) Target Installs

To create a campaign, you simply need to:

1.Sign Up to the platform(free). Then verify your account.
Add Your App’s Market URL

  1. Payment : Add Funds in your account by PayPal,Bitcoin,Skrill .

3.Integrate with Tracking Tools: steamseo offers an integration with functional and commonly used app tracking tools to accelerate and sustain growth in the app market.

4.Launch Campaign: Start driving growth with steamseo. After that, you can monitor the ad performance by exporting daily, weekly, monthly reports that show in-app events and app store metrics so that optimize your ads by finding the most profitable customers and channels at the lowest costs.

How to implement a push notification which sends a notification every day at the same time

$
0
0

Hello i'm working at the moment on a app which get informations from a backend. Customers can add infomations with the backend an can choose that users get a push notification. The problem is that the push notification becomes send directly after I add a new information with the backend. I wanna achieve that the notification will send at a specific time.

Service not starting to sendRegistrationToServer while implementing Xamarin.Forms Push Notifications

$
0
0

Hello guys,
I am implementing push notifications in a xamarin.forms application. iOS part works fine. I can send and receive notifications with it. But for Android, I can send notifications via an API backend but can not receive notifications. Reason is that device is not getting registered with Firebase cloud messaging. I placed degubber and came to know that method inside **MyFirebaseIIDService **that registers device with FCM never gets called. I am pasting below code for my main Activity and Android Manifest. Please have a look and suggest some solutions. Thanks

MainActivity:

using System;

using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Xamarin.Forms;
using Firebase.Messaging;
using System.Diagnostics;
using Firebase.Iid;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.MobileServices;
using Android.Gms.Common;
using Newtonsoft.Json.Linq;
using static Android.Manifest;

namespace Push.Droid
{
    [Activity(Label = "Push", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);
            LoadApplication(new App());

            IsPlayServicesAvailable();

#if DEBUG
            // Force refresh of the token. If we redeploy the app, no new token will be sent but the old one will
            // be invalid.
            Task.Run(() =>
            {
                // This may not be executed on the main thread.
                FirebaseInstanceId.Instance.DeleteInstanceId();
                Console.WriteLine("Forced token: " + FirebaseInstanceId.Instance.Token);
            });
#endif
        }

        public bool IsPlayServicesAvailable()
        {
            int resultCode = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(this);
            if (resultCode != ConnectionResult.Success)
            {
                if (GoogleApiAvailability.Instance.IsUserResolvableError(resultCode))
                {
                    // In a real project you can give the user a chance to fix the issue.
                    Console.WriteLine($"Error: {GoogleApiAvailability.Instance.GetErrorString(resultCode)}");
                }
                else
                {
                    Console.WriteLine("Error: Play services not supported!");
                    Finish();
                }
                return false;
            }
            else
            {
                Console.WriteLine("Play Services available.");
                return true;
            }
        }
    }

    // This service handles the device's registration with FCM.
    [Service]
    [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
    public class MyFirebaseIIDService : FirebaseInstanceIdService
    {
        public override void OnTokenRefresh()
        {
            var refreshedToken = FirebaseInstanceId.Instance.Token;
            Console.WriteLine($"Token received: {refreshedToken}");
            SendRegistrationToServerAsync(refreshedToken);
        }

        async Task SendRegistrationToServerAsync(string token)
        {
            try
            {
                // Formats: https://firebase.google.com/docs/cloud-messaging/concept-options
                // The "notification" format will automatically displayed in the notification center if the 
                // app is not in the foreground.
                const string templateBodyFCM =
                    "{" +
                        "\"notification\" : {" +
                        "\"body\" : \"$(messageParam)\"," +
                          "\"title\" : \"Xamarin University\"," +
                        "\"icon\" : \"myicon\" }" +
                    "}";

                var templates = new JObject();
                templates["genericMessage"] = new JObject
                {
                    {"body", templateBodyFCM}
                };

                var client = new MobileServiceClient(Push.App.MobileServiceUrl);
                var push = client.GetPush();

                await push.RegisterAsync(token, templates);

                // Push object contains installation ID afterwards.
                Console.WriteLine(push.InstallationId.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Debugger.Break();
            }
        }
    }

    // This service is used if app is in the foreground and a message is received.
    [Service]
    [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]

    public class MyFirebaseMessagingService : FirebaseMessagingService
    {
        public override void OnMessageReceived(RemoteMessage message)
        {
            base.OnMessageReceived(message);

            Console.WriteLine("Received: " + message);

            // Android supports different message payloads. To use the code below it must be something like this (you can paste this into Azure test send window):
            // {
            //   "notification" : {
            //      "body" : "The body",
            //                 "title" : "The title",
            //                 "icon" : "myicon
            //   }
            // }
            try
            {
                var msg = message.GetNotification().Body;
                MessagingCenter.Send<object, string>(this, Push.App.NotificationReceivedKey, msg);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error extracting message: " + ex);
            }
        }
    }
}

AndroidManifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.xamarin.xamarinnotif" android:installLocation="auto">
    <uses-sdk android:minSdkVersion="15" />
    <application android:label="Push">
    <receiver android:name="com.google.android.gms.gcm.GcmReceiver"
              android:exported="true"

              android:permission="com.google.android.c2dm.permission.SEND">
      <service android:enabled="true" android:name="com.xamarin.xamarinnotif.Push.Droid" />

      <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
        <category android:name="com.xamarin.xamarinnotif" />
      </intent-filter>
    </receiver>

  </application>
  <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
  <uses-permission android:name="android.permission.WAKE_LOCK" />
  <uses-permission android:name="android.permission.INTERNET" />
  <permission android:name="com.xamarin.xamarinnotif.permission.C2D_MESSAGE" android:protectionLevel="signature" />
  <uses-permission android:name="com.xamarin.xamarinnotif.permission.C2D_MESSAGE" />
</manifest>

How to open image in fullscreen when clicked

$
0
0

Hello guys thank you for reading my question, i am new to xamarin and i want to make it so when i click on image it opens it in fullscreen.
MY CODE:


<Image.GestureRecognizers>

</Image.GestureRecognizers

C# code:
void OnTapGestureRecognizerTapped7(object sender, EventArgs args)
{

}

Handle Button Pressed / Hover

$
0
0

Hi,
I want to change programmatically the style of an element when user just pressed a button (not clicked).
So for that I need a callback fonction (like Clicked="FunctionToCall" in xaml, but for pressed="...") but I don't find this function.
I've try command and trigger and I search for a solution since 2 days...

Thanks for your help !

custom viewrenderer for UILabel overlaps text inside list view on scroll

$
0
0

I am using a couple of sources to make a custom renderer for a label that can display htmlstring and has data detectors. On android, it works perfectly, but ios implementation has some issues. Here's the ios implementation :

`using System.ComponentModel;
using CoreGraphics;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(HyperLinkLabel), typeof(HyperLinkLabelRenderer))]
namespace YourNameSpace
{
public class HyperLinkLabelRenderer : ViewRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs e)
{
base.OnElementChanged(e);

        var view = (HyperLinkLabel)Element;
        if (view == null) return;

        var attr = new NSAttributedStringDocumentAttributes();
        var nsError = new NSError();
        attr.DocumentType = NSDocumentType.HTML;

        var myHtmlData = NSData.FromString(view.Text, NSStringEncoding.Unicode);

        UITextView uilabelleftside = new UITextView(new CGRect(0, 0, view.Width, view.Height));
        //uilabelleftside.Text = view.Text;
        uilabelleftside.Editable = false;
        uilabelleftside.AttributedText = new NSAttributedString(myHtmlData, attr, ref nsError);
        uilabelleftside.Font = UIFont.SystemFontOfSize((float)view.FontSize);


        // Setting the data detector types mask to capture all types of link-able data
        uilabelleftside.DataDetectorTypes = UIDataDetectorType.All;
        uilabelleftside.BackgroundColor = UIColor.Clear;

        // overriding Xamarin Forms Label and replace with our native control
        SetNativeControl(uilabelleftside);
    }

    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);

        if (e.PropertyName == Label.TextProperty.PropertyName)
        {
            var view = (HyperLinkLabel)Element;
            if (view == null) return;

            var attr = new NSAttributedStringDocumentAttributes();
            var nsError = new NSError();
            attr.DocumentType = NSDocumentType.HTML;

            var myHtmlData = NSData.FromString(view.Text, NSStringEncoding.Unicode);

            UITextView uilabelleftside = new UITextView(new CGRect(0, 0, view.Width, view.Height));

            uilabelleftside.AttributedText = new NSAttributedString(myHtmlData, attr, ref nsError);
            uilabelleftside.Font = UIFont.SystemFontOfSize((float)view.FontSize);
            uilabelleftside.Editable = false;

            // Setting the data detector types mask to capture all types of link-able data
            uilabelleftside.DataDetectorTypes = UIDataDetectorType.All;
            uilabelleftside.BackgroundColor = UIColor.Clear;

            // overriding Xamarin Forms Label and replace with our native control
            SetNativeControl(uilabelleftside);
        }
    }
}

}
`

When I scroll down or up and an item reappears, it fires OnElementChanged with different values and this causes the text of the renderer to overlap.
Here's my Xaml:

<TabbedPage.ItemTemplate> <DataTemplate> <ContentPage Title="{Binding title}"> <ListView ItemsSource="{Binding Posts}"> <ListView.RowHeight> <OnPlatform x:TypeArguments="x:Int32" iOS="200" Android="220"/> </ListView.RowHeight> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <Grid Padding="8"> <Grid.ColumnDefinitions> <ColumnDefinition Width = "50"/> <ColumnDefinition Width = "*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height = "40"/> <RowDefinition Height = "3"/> <RowDefinition Height = "*"/> <RowDefinition Height = "30"/> </Grid.RowDefinitions> <Image Grid.Column = "0" Grid.Row = "0" Source = "{Binding author.avatar_url}" Aspect = "AspectFill" WidthRequest = "40" HeightRequest = "40" HorizontalOptions = "Center" VerticalOptions = "Center"/> <Grid Grid.Column = "1"> <Grid.ColumnDefinitions> <ColumnDefinition Width = "*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height = "15"/> <RowDefinition> <OnPlatform x:TypeArguments = "GridLength" iOS="10" Android="15" /> </RowDefinition> </Grid.RowDefinitions> <Label Grid.Row = "0" Style = "{StaticResource authorName}" Text="{Binding author.full_name}" /> <Label Grid.Row = "1" Style = "{StaticResource proffInfo}" Text="{Binding author.proffInfo}" /> </Grid> <Grid x:Name = "postContent" Grid.Row = "2" Grid.Column = "0" Grid.ColumnSpan = "2" > <Grid.RowDefinitions> <RowDefinition Height = "30"/> <RowDefinition Height = "*"/> </Grid.RowDefinitions> <Label Grid.Row = "0 " Style = "{StaticResource heading1}" Text = "{Binding title}" /> <!--<WebView Grid.Row = "1"> <WebView.Source> <HtmlWebViewSource Html="{Binding html_content}"/> </WebView.Source> </WebView>--> <renderers:HyperLinkLabel Grid.Row = "1" Text="{Binding html_content}" /> </Grid> </Grid> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView> </ContentPage> </DataTemplate> </TabbedPage.ItemTemplate>

The xaml shouldn't be an issue cause it renders on android just fine.

Map Renderer with custom Pin

$
0
0

Hi to all, I followed this guide: https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/custom-renderer/map/customized-pin/
to develop my app.
The pins work correctly but when I try to reach my device location on the map, I get a null pointer like this:

System.NullReferenceException: Object reference not set to an instance of an object
at at (wrapper managed-to-native) UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)
at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Users/builder/data/lanes/3969/44931ae8/source/xamarin-macios/src/UIKit/UIApplication.cs:79
at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00038] in /Users/builder/data/lanes/3969/44931ae8/source/xamarin-macios/src/UIKit/UIApplication.cs:63
at blind.iOS.Application.Main (System.String[] args) [0x00008] in /Users/alessandroa/Projects/blind/iOS/Main.cs:17

I add my location with this:

    nativeMap.ShowsUserLocation = true;
    nativeMap.SetUserTrackingMode(MKUserTrackingMode.Follow, true);

in the OnElementChanged method.
Any suggestions?

Thanks a lot!


How to change the MasterDetailPage.MasterBehavior depending on the width

$
0
0

Hello,

I write a Xamarin forms application for UWP and try to use an adaptive UI. On a small screen I want the MasterBehavior to be 'popover' and on a large screen it should be 'split'. I registered the SizeChanged event and change the MasterBehaviour but it does not work. What must I do to make it work?

public MainPage()
        {
            this.InitializeComponent();
            SizeChanged += OnSizeChanged;
        }

        private void OnSizeChanged(object sender, EventArgs e)
        {
            if ( Width < 700)
            {
                this.MasterBehavior = MasterBehavior.Popover;
                UpdateChildrenLayout();
            } else
            {
                this.MasterBehavior = MasterBehavior.Split;
                UpdateChildrenLayout();
            }
        }

Is turn-by-turn navigation possible in a Xamarin.Forms app?

$
0
0

I am writing an app with Xamarin Forms where I need to have some form of in-app turn-by-turn navigation features. Something similar to Google Maps' directions, but using a Xamarin Maps approach or a third-party plugin. I found a couple of third party providers, but most provide support or APIs for native Android in Java or iOS in Swift. Is there any solution for a Forms app?
Thank you.

How to implement push notification like gmail, Facebook did in their app through my own database?

$
0
0

I need to notify to user when anyone send message to another one through app.

UWP LoadFromXaml Causes Exception 'System.PlatformNotSupportedException'

$
0
0

Does anyone have a clue as to why this exception occurs on UWP?
Exception thrown: 'System.PlatformNotSupportedException' in System.Private.Reflection.Execution.dll

It seems to only occur on LoadFromXaml which is stock code under InitializeComponent on all forms. Thanks.

Link to screenshot
imgur.com/a/yhVJg

Upload MultipartFormDataContent with IntentService

$
0
0

I am writing a PCL project targeting mainly iOS and Android and I am experiencing a problem with the uploading of the data that is captured. I want to use an IntentService to do this because of the control it exerts in processing only one package at a time. I would please like some assistance in accomplishing this as I cannot find anything to assist with this. My package consists of multiple images and text that needs to be uploaded to a certain service.

Viewing all 77050 articles
Browse latest View live