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

Animate growth of ScrollView which is expanding from the bottom of the page?

$
0
0

We've got a ScrollView which I've set with a VerticalOptions of "End", so that when we add content to it at runtime it 'grows' from the bottom.

We're scrolling to the end when adding content, with animation. This looks good when the ScrollView is full and is actually scrolling.

However, when content is added to the ScrollView, the new content appears immediately with no animation.

Any thoughts on how to animate the growth of the ScrollView as the new content is added? Ideally I'd like it to slide up, like the animated scroll when it's full.

We're using a RepeaterView as the content of the ScrollView, if that's relevant.


Foreground Service problem on Oreo 8.1 and Pie 9.0

$
0
0

I have problems with Oreo 8.1 and Pie 9.0. When my pedometer app is open or on the background it is counting steps, but not when the app is closed. Also after closing app notification icon disappearing from the phone screen. Tested on Oreo 8.0 using foreground service and it is working fine with notification icon on top left corner of phone screen and counting steps when the app is closed. Tested also on android Nougat without foreground services and working fine. I cannot find the problem maybe it is something with remove, destroy, resume, stop, pause functions?

BootReceiver.cs

[BroadcastReceiver(Enabled = true, Exported = true, DirectBootAware = true)]
    [IntentFilter(new string[] { Intent.ActionBootCompleted, Intent.ActionLockedBootCompleted, "android.intent.action.QUICKBOOT_POWERON", "com.htc.intent.action.QUICKBOOT_POWERON" })]
    public class BootReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
             var stepServiceIntent = new Intent(context, typeof(StepService));
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            {
                context.StartForegroundService(stepServiceIntent);
            }
            else
            {
                context.StartService(stepServiceIntent);
            }
        }
    }

StepServiceBinder.cs

public class StepServiceBinder : Binder
    {
        StepService stepService;
        public StepServiceBinder(StepService service)
        {
            this.stepService = service;
        }

        public StepService StepService
        {
            get { return stepService; }
        }
    }

StepServiceConnection.cs

 public class StepServiceConnection : Java.Lang.Object, IServiceConnection
    {
        MainActivity activity;

        public StepServiceConnection(MainActivity activity)
        {
            this.activity = activity;
        }

        public void OnServiceConnected(ComponentName name, IBinder service)
        {
            var serviceBinder = service as StepServiceBinder;
            if (serviceBinder != null)
            {
                activity.Binder = serviceBinder;
                activity.IsBound = true;
            }
        }

        public void OnServiceDisconnected(ComponentName name)
        {
            activity.IsBound = false;
        }
    }

MainActivity.cs

 [Activity(Label = "My Pedometer", Icon = "@mipmap/icon", Theme = "@style/MainTheme", LaunchMode = LaunchMode.SingleTask, MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        public bool IsBound { get; set; }
        private StepServiceBinder binder;
        private bool registered;
        private Handler handler;
        private bool firstRun = true;
        private StepServiceConnection serviceConnection;
        public StepServiceBinder Binder
        {
            get { return binder; }
            set
            {
                binder = value;
                if (binder == null)
                    return;

                HandlePropertyChanged(null, new System.ComponentModel.PropertyChangedEventArgs("StepsToday"));

                if (registered)
                    binder.StepService.PropertyChanged -= HandlePropertyChanged;

                binder.StepService.PropertyChanged += HandlePropertyChanged;
                registered = true;
            }
        }

        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);
            Xamarin.Forms.Forms.Init(this, savedInstanceState);
            StartStepService();        
            handler = new Handler();
            handler.PostDelayed(() => UpdateUI(), 500);
           LoadApplication(new App());

        }

      private void StartStepService()
        {
            try
            {
                var service = new Intent(this, typeof(StepService));

                if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
                {
                    StartForegroundService(service);
                }
                else
                {
                   StartService(service);
                }

            }
            catch (Exception ex)
            {               
                Console.WriteLine("Exception {0}.", ex.Message);
            }
        }

        protected override void OnStop()
        {
            base.OnStop();
            if (IsBound)
            {
                UnbindService(serviceConnection);
                IsBound = false;
            }
        }

        protected override void OnDestroy()
        {
            base.OnDestroy();
            if (IsBound)
            {
                UnbindService(serviceConnection);
                IsBound = false;
            }
        }

        protected override void OnStart()
        {
            base.OnStart();

            if (!firstRun)
                StartStepService();

            if (IsBound)
                return;

            var serviceIntent = new Intent(this, typeof(StepService));
            serviceConnection = new StepServiceConnection(this);
            BindService(serviceIntent, serviceConnection, Bind.AutoCreate);
        }

        protected override void OnPause()
        {
            base.OnPause();
            if (registered && binder != null)
            {
                binder.StepService.PropertyChanged -= HandlePropertyChanged;
                registered = false;
            }
        }

        protected override void OnResume()
        {
            base.OnResume();
            if (!firstRun)
            {
                if (handler == null)
                    handler = new Handler();
                handler.PostDelayed(() => UpdateUI(), 500);
            }

            firstRun = false;

            if (!registered && binder != null)
            {
                binder.StepService.PropertyChanged += HandlePropertyChanged;
                registered = true;
            }
        }

        void HandlePropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName != "StepsToday")
                return;
            UpdateUI();
        }

        private void UpdateUI()
        {
            RunOnUiThread(() =>
            {
                long steps = 0;
                var showWaring = false;
                if (Binder == null)
                {
                    if (Utils.IsSameDay)
                        steps = Settings.CurrentDaySteps;
                }
                else
                {
                    steps = Binder.StepService.StepsToday;
                    showWaring = binder.StepService.WarningState;
                }

                Settings.CurrentDaySteps = steps;
            });
        }
    }

StepService.cs

[Service(Enabled = true)]
    [IntentFilter(new String[] { "com.PedometerApp.StepService" })]
    public class StepService :  Service, ISensorEventListener, INotifyPropertyChanged
    {
        private SensorManager sManager;
        private bool isRunning;
        private long stepsToday = 0;
        public bool WarningState
        {
            get;
            set;
        }

        public long StepsToday
        {
            get { return stepsToday; }
            set
            {
                if (stepsToday == value)
                    return;

                stepsToday = value;
                OnPropertyChanged("StepsToday");
                Settings.CurrentDaySteps = value;
                MessagingCenter.Send<object, long>(this, "Steps", Settings.CurrentDaySteps);
            }
        }

        public const string PRIMARY_NOTIF_CHANNEL = "exampleChannel";
        public const int SERVICE_RUNNING_NOTIFICATION_ID = 10000;
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            RegisterForService();
            var warning = false;
            if (intent != null)
                warning = intent.GetBooleanExtra("warning", false);
            Startup();
            return StartCommandResult.Sticky;
        }

        private void RegisterForService()
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                var channel = new NotificationChannel(PRIMARY_NOTIF_CHANNEL, "Pedometer Service Channel", NotificationImportance.Low)
                {
                    Description = "Foreground Service Channel"
                };

                var notificationManager = (NotificationManager)GetSystemService(NotificationService);
                notificationManager.CreateNotificationChannel(channel);

                var notification = new Notification.Builder(this, PRIMARY_NOTIF_CHANNEL)
                .SetContentTitle("Service")
                .SetContentText("Running")
                .SetSmallIcon(Resource.Drawable.ic_stat_name)
                .SetContentIntent(BuildIntentToShowMainActivity())
                .SetOngoing(true)
                .Build();
                StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
            }
            else
            {
                BuildIntentToShowMainActivity();
            }
        }

        PendingIntent BuildIntentToShowMainActivity()
        {
            var alarmManager = ((AlarmManager)ApplicationContext.GetSystemService(AlarmService));
            var intent2 = new Intent(this, typeof(StepService));
            intent2.PutExtra("warning", WarningState);
            var stepIntent = PendingIntent.GetService(ApplicationContext, 200, intent2, PendingIntentFlags.UpdateCurrent);
            alarmManager.Set(AlarmType.Rtc, Java.Lang.JavaSystem
              .CurrentTimeMillis() + 1000 * 60 * 60, stepIntent);

            return stepIntent;
        }



        public override void OnTaskRemoved(Intent rootIntent)
        {
            base.OnTaskRemoved(rootIntent);

            UnregisterListeners();
            var intent = new Intent(this, typeof(StepService));
            intent.PutExtra("warning", WarningState);
            ((AlarmManager)GetSystemService(AlarmService)).Set(AlarmType.Rtc, Java.Lang.JavaSystem
                .CurrentTimeMillis() + 500,
                PendingIntent.GetService(this, 201, intent, 0));
        }

        private void Startup(bool warning = false)
        {
            CrunchDates(true);

            if (!isRunning)
            {
                RegisterListeners();
                WarningState = warning;
            }

            isRunning = true;
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
            UnregisterListeners();
            isRunning = false;
            CrunchDates();
        }

        void RegisterListeners()
        {
            sManager = GetSystemService(SensorService) as SensorManager;
            sManager.RegisterListener(this, sManager.GetDefaultSensor(SensorType.StepCounter), SensorDelay.Ui);
        }


        void UnregisterListeners()
        {
            if (!isRunning)
                return; 
            try
            {
                var sensorManager = (SensorManager)GetSystemService(Context.SensorService);
                sensorManager.UnregisterListener(this);

                isRunning = false;
            }
            catch (Exception ex)
            {

            }
        }

        StepServiceBinder binder;
        public override Android.OS.IBinder OnBind(Android.Content.Intent intent)
        {
            binder = new StepServiceBinder(this);
            return binder;
        }

        public void OnAccuracyChanged(Sensor sensor, SensorStatus accuracy)
        {
            //do nothing here
        }

        public void AddSteps(long count)
        {
            if (lastSteps == 0)
            {
                lastSteps = count;
            }


            newSteps = count - lastSteps;


            if (newSteps < 0)
                newSteps = 1;
            else if (newSteps > 100)
                newSteps = 1;


            lastSteps = count;
            CrunchDates();

            Settings.TotalSteps += newSteps;

            StepsToday = Settings.TotalSteps - Settings.StepsBeforeToday;
        }

        long newSteps = 0;
        long lastSteps = 0;
        public void OnSensorChanged(SensorEvent e)
        {
            if (lastSteps < 0)
                lastSteps = 0;
            var count = (long)e.Values[0];
            WarningState = false;
            AddSteps(count);
        }

        private void CrunchDates(bool startup = false)
        {
            if (!Utils.IsSameDay)
            {

                var yesterday = Settings.CurrentDay;
                var dayEntry = StepEntryManager.GetStepEntry(yesterday);
                if (dayEntry == null || dayEntry.Date.DayOfYear != yesterday.DayOfYear)
                {
                    dayEntry = new StepEntry();
                }

                dayEntry.Date = yesterday;
                dayEntry.Steps = Settings.CurrentDaySteps;

                Settings.CurrentDay = DateTime.Today;
                Settings.CurrentDaySteps = 0;
                Settings.StepsBeforeToday = Settings.TotalSteps;
                StepsToday = 0;
                try
                {
                    StepEntryManager.SaveStepEntry(dayEntry);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error {0}", ex.Message);
                }

            }

            else if (startup)
            {
                StepsToday = Settings.TotalSteps - Settings.StepsBeforeToday;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string name)
        {
            if (PropertyChanged == null)
                return;

            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }

    }

***Manifest.xml ***

<manifest android:versionName="1.1" package="com.PedometerApp" android:installLocation="internalOnly" android:versionCode="11">
    <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="27" />
    <application android:label="My Pedometer" android:icon="@drawable/logo">    </application>
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
</manifest>

How to open PDF or TXT file in default app on Xamarin Forms

$
0
0

I am going to open document using default app in Xamarin Forms. I tried already this approach but it doesn't work for me and I am not sure what is the reason.

Device.OpenUri(new Uri(FILE_PATH));

Please give me great solution if anyone knows how to handle it. Thanks.

MasterDetailPage VoiceOver problem

$
0
0

Hello guys, I have an app built with MasterDetailPage architecture.
I'm trying to make the app accessible but, I noticed that in IOS I have the following problem:
If i open the MasterPage (where i have the navigation menu), the detail page slides (native behaviour) but voiceover read first all the detail page (that should be hidden/lower priority) and after the masterpage menu. How can I force to read the MasterPage first? (that in my opinion should be the default behaviour since I'm opening the Masterpage menu).
Thanks a lot!

[Xamarin.IOS] [Xamarin.Forms] Soft Keyboard hides Entry at bottom of page.

$
0
0

[Xamarin.Forms] [Xamarin.IOS] I have a chat page which has a listview of messages and a horizontal stack at bottom (which contains an entry for new message and a send button). My problem is that in iOS, on tapping the entry, the Keyboard appears and hides the entry. I want it to scroll the page up such that the entry and the send button still remain visible. I have tried searching in Xamarin forums but couldn't find any proper solution. Everything works fine in Android.

Can I bind to a command from a ListView's parent when I'm using ViewCells in a separate file?

$
0
0

My app needs to switch between two different ViewCells, so I've been using a DataTemplateSelector for this like so:

using MyOrg.PageModels;
using Xamarin.Forms;

namespace MyOrg.ViewCells
{
    public class ItemDataTemplateSelector : DataTemplateSelector
    {
        public ItemDataTemplateSelector()
        {
            // Retain instances 
            SimpleTemplate = new DataTemplate(typeof(SimpleItemViewCell));
            DetailedTemplate = new DataTemplate(typeof(DetailedItemViewCell));
        }

        protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
        {
            return ((MyPageModel)container.BindingContext).SimpleModeEnabled ? SimpleTemplate : DetailedTemplate;
        }

        private readonly DataTemplate SimpleTemplate;
        private readonly DataTemplate DetailedTemplate;
    }
}

The issue now is that when creating these cells in the constructor, it's using the ViewCells from separate files to the actual page:

 <ViewCell xmlns="http://xamarin.com/schemas/2014/forms" 
           xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
           x:Class="MyOrg.ViewCells.SimpleItemViewCell">
     <Frame CornerRadius="2.5"
             Margin="5, 2.5"
             Padding="10" >
         <StackLayout Orientation="Horizontal">
             <Label Text="{Binding Number}" 
                    TextColor="{StaticResource MidBlue}" 
                    FontSize="Large" />
             <Label Text="{Binding DetailText}" 
                    TextColor="Black" 
                    FontSize="Large" 
                    LineBreakMode="TailTruncation"/>
         </StackLayout>
     </Frame>
     <ViewCell.ContextActions>
         <MenuItem
                   Command="{Binding Path=ParentBindingContext.DeleteSelectedCommand, Source={x:Reference MyPageName}}"
                   Icon="sharp_delete_white_24.png"/>
     </ViewCell.ContextActions>
 </ViewCell>

MyPageName refers to the name of my page from a content page file. But I don't have access to this from this separate file, so the command doesn't fire.

Is there any way I can pass a reference to the page into each of these ViewCells?

WPF ClickGestureRecognizer

$
0
0

Is ClickGestureRecognizer implemented for WPF yet?

If so, could someone please show a usage example?

If not, can someone please suggest a workaround?

I've tried using ClickGestureRecognizer but can't seem to get the event to fire, though tap does.

<BoxView BackgroundColor="#55555555">
    <BoxView.GestureRecognizers>
        <ClickGestureRecognizer Clicked="ClickGestureRecognizer_OnClicked" />
    </BoxView.GestureRecognizers>
</BoxView>

I need to capture a mouse click event and know the mouse position relative to the clicked element.

Problem with "Zombie pages" and MessagingCenter subscribers that keep living after unsubscribe

$
0
0

Hi everyone,

I'm having a bit of an issue with so called "zombie" pages and messaging center subscribers.
Let's say my application is structured as follows: LoginPage -> MenuPage -> PageA -> PageB

In each of the PageA and PageB I subscribe to the messaging center messages in the OnAppearing method and then unsubscribe in the OnDisappearing method, since I only want to listen to the messages when the page is active (displayed). If I navigate directly from page to page everything is working correctly.

However I am checking the user session when OnAppearing of each of the PageA and PageB is called, and if the user session has expired, I return the user to the first page (LoginPage). In order to achieve this, I created a helper method in my App class, which replaced the current MainPage (as was suggested on other threads on this page):

public void ClearNavigation()
{
    MainPage = new NavigationPage(new Login());
}

So for example if I call the ClearNavigation in my PageB page, the OnDisappearing method will be called and with it the unsubscribe call to the message. After that, the LoginPage will be shown. I'm checking the NavigationStack size, and it is 1, so everything is looking ok.

However:
If I trigger a message, that each of the pages is subscribing/unsubscribing to, something really weird will happen. The message will get to the PageB (it will actually trigger a breakpoint in the PageB), which is not in the current NavigationStack, and was unsubscribed in the OnDisappearing method (and OnAppearing was not called after that).

So 2 things are really strange here:
1. The page still lives in memory, after the MainPage was replaced. In fact all pages still live in the memory, since if I check the NavigationStack of the page which receives the message, it's different than the one I'm currently on (the one with only 1 page) I'm guessing this is not the correct way to reset your application in that case...)? I tried using the .PopToRootAsync() method, but that usually results into exception and Application crash.
2. The message is hitting it's subscriber, even if it was unsubscribed (and not subscribed again). So it looks like the OnDisappearing does not finish executing in the event that the MainPage is replaced, or something?)

Does anyone has any similar experience or would be able to give me a insight into what is causing this strange and unwanted behavior? Is this normal behaviour or maybe an Xamarin.Forms bug? I am using the version 3.6, but the problem was the same in the 3.5, I didn't test any other versions.

BR,
Denis


How design grid like this in forecah loop

$
0
0

Hii community..
i need to design grid like below .
i have 5 records that 5 records i need to show five times how to do using foreach loop in

thanks in advance

Mask

$
0
0

<Entry.Behaviors> <behavior:MaskedBehavior Mask="XXX,XX"/> </Entry.Behaviors>

Hello everyone,

Can somebody tell me if i can write a Mask from right to left,
Thank you!

Connect programmaticly android device to wif

$
0
0

Hii everyone,

I need some help i m trying to set a new hot and connect to it , i sow many solutions in internet that are all in the same topic, in thous solution I m able to desconect my current wifi and change the name of host (SSID), but the security style on none even if i added the PreSharedKey and all setting managment to allow devise for setting but anable to add this key and connect automaticly to thi wifi i m working with the latest version of host manager and the device in an honeywell, please some help and thank you.

Meriem

Get Wifi info with android 9

$
0
0

Hi,

I'm building an app where I need to know the wifi info like the ssid. Until android 8 it worked fine, but since I update to android 9 it gives back "unknown_ssid".
I used a Dependency:

This is the interface in the PCL:

    public interface IWlanInfo
    {
        string GetCurrentSSID();

        string GetCurrentBSSID();

        bool GetCurrentIsHidden();
    }

This is the implementation at the droid project:

[assembly: Dependency(typeof(DroidProject.Droid.WlanInfoAndroid))]
namespace DroidProject.Droid
{    
    public class WlanInfoAndroid : IWlanInfo
    {        
        public string GetCurrentBSSID()
        {                                    
            return ((WifiManager)Android.App.Application.Context.GetSystemService(Context.WifiService)).ConnectionInfo.BSSID;
        }

        public bool GetCurrentIsHidden()
        {
            return ((WifiManager)Android.App.Application.Context.GetSystemService(Context.WifiService)).ConnectionInfo.HiddenSSID;
        }

        public string GetCurrentSSID()
        {
            return ((WifiManager)Android.App.Application.Context.GetSystemService(Context.WifiService)).ConnectionInfo.SSID;
        }
    }
}

And this is how I call it at the PCL:

        var ssid = DependencyService.Get<IWlanInfo>().GetCurrentSSID().Trim('"');
            var bssid = DependencyService.Get<IWlanInfo>().GetCurrentBSSID();
            var isHidden = DependencyService.Get<IWlanInfo>().GetCurrentIsHidden();

Does anybody know how I can make it work again?
Thanks in advance!

Xamarin Live Player vs Gorilla Player

$
0
0

Can someone tell me what is better at the current moment? Xamarin Live Player is official, but still in development. Gorilla player seems more stable. Did you test them both so you can tell me the differences?

How to show ActivityIndicator that covers whole screen including Navigation bar - Xamarin Forms

$
0
0

My code for ActivityIndicator is below:

    <ActivityIndicator x:Name="actWebRequest"
                    Color="White"
                    IsVisible="{Binding IsLoading}"
                    IsRunning="{Binding IsLoading}"
                    AbsoluteLayout.LayoutBounds="0, 0, 1, 1"
                    AbsoluteLayout.LayoutFlags= "All" 
                    BackgroundColor="#70383838"/>

I know, I can put it inside absolute layout or any other layour.

MY NEED:
I would like to show it for the whole screen which should also overlay above Navigation bar's back button, title and slide menu icon on my top right side in Navigation bar.
I MEAN FOR THE WHOLE SCREEN.

How can I achieve this using Xaml in Xamarin Forms.

Thank you a lot in advance for the help. :smiley:

Label in viewcell disappearing when updating listview's itemssource on locked Android device

$
0
0

I am running into a bug with labels in my viewcells. I managed to capture this behaviour in the following test app:

C# code:

using System;
using System.Collections.Generic;
using Xamarin.Forms;

namespace AndroidLockscreenIssue
{
    public partial class AndroidLockscreenIssuePage : ContentPage
    {
        public AndroidLockscreenIssuePage()
        {
            InitializeComponent();

            list1.ItemsSource = new List<Item>
            {
                new Item("Item title 1", "Item detail 1"),
                new Item("Item title 2", "Item detail 2"),
                new Item("Item title 3", "Item detail 3"),
            };
            list2.ItemsSource = list1.ItemsSource;
        }

        /// <summary>
        /// Trigger bugging
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        public void OnClick(object sender, EventArgs e){
            StartTimer();
            bugbtn.IsEnabled = false;
        }

        /// <summary>
        /// Reset list sources> 
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        public void OnFixClick(object sender, EventArgs e)
        {
            var source = list1.ItemsSource;
            list1.ItemsSource = null;
            list1.ItemsSource = source;
            list2.ItemsSource = null;
            list2.ItemsSource = source;
            fixbtn.IsEnabled = false;
            bugbtn.IsEnabled = true;
        }

        /// <summary>
        /// Shuffle the list a bit in 5 seconds.
        /// </summary>
        public void StartTimer()
        {
            Device.StartTimer(TimeSpan.FromSeconds(5), delegate
            {
                Device.BeginInvokeOnMainThread(delegate
                {
                    var coll = ((List<Item>)list1.ItemsSource);
                    var firstitem = coll[0];
                    coll.RemoveAt(0);
                    coll.Insert(coll.Count-1, firstitem);
                    list1.ItemsSource = null;
                    list1.ItemsSource = coll;
                    list2.ItemsSource = null;
                    list2.ItemsSource = coll;
                    System.Diagnostics.Debug.WriteLine("TIMER: updating list collection");
                    fixbtn.IsEnabled = true;
                });
                return false;
            });
        }
    }

    public class Item
    {
        public string Text { get; set; }
        public string Detail { get; set; }
        public Item(string text, string detail)
        {
            Text = text;
            Detail = detail;
        }
    }
}

xaml code:

<?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:AndroidLockscreenIssue" x:Class="AndroidLockscreenIssue.AndroidLockscreenIssuePage">
    <StackLayout>
        <Label Text="Press the 'Bug it!' button to trigger a list change in 5 seconds. Lock your screen, wait 5+ seconds and unlock your screen. The list will be 'empty'." VerticalOptions="Center" HorizontalOptions="Center" />
        <Button Text="Bug it!" Clicked="OnClick" x:Name="bugbtn"/>
        <Button Text="Fix it!" Clicked="OnFixClick" x:Name="fixbtn" IsEnabled="false"/>
        <Label Text="Bugged list (ViewCell)"/>
        <ListView x:Name="list1">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal">
                            <Label Text="{Binding Text}" FontSize="Large"/>
                            <Label Text="{Binding Detail}"/>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Label Text="OK list (TextCell)"/>
        <ListView x:Name="list2">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextCell Text="{Binding Text}" Detail="{Binding Detail}"/>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage>

When I press the 'bug it!' button, it triggers a timer that will change the itemssource within 5 seconds. If you lock your android device before this update happens and unlock after it happened, the list with ViewCells will not render the labels whilst the list with TextCells does render it's text just fine. Is there any way to fix this?


Long Press Background Color Change in ListView

$
0
0

Is it possible to change the background color on long press (Context Menu ) in Xamarin Forms in android ?
I have have tried customizing the theme but it doesn't work or maybe I am wrong somewhere !

why can I build my iOS project in windows ?

$
0
0

I knew I can't build Xamarin.iOS project on my windows machine, but it happened!

I have a Xamarin.Forms project and when I build my application or my solution the output has not errors. How is it possible?

Output should tell me that Xamarin.iOS cannot compile his code.

Autosize font label

$
0
0

I have seen a custom approach to autosize the font of a label, but I am missing such a built-in feature.
How do you others handle different font size on different systems / resolutions, please?

ScrollView ScrollToAsync resulting in blank screen on iOS

$
0
0

Background
We have a page where we have a bound RepeaterView within a ScrollView. We're adding Questions to the bound collection as the user answers questions (the aim is to give a series of questions, scrolling off the top as the user progresses).

We want the ScrollView to scroll to the bottom as we add Questions.

To do this, I've created an Event which we raise when we add a Question, and added a handler in the Page. I'm subscribing/unsubscribing on the Appearing/Disappearing events for the page to avoid memory leaks etc.

The Problem
On Android this works fine. But on iOS, the ScrollView goes blank. However, if I background the app and bring it back to the foreground (by tapping the Home button and then the app icon, the screen then refreshes.

Therefore it appears that the Page isn't being refreshed properly by my code.

My XAML code:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MvvmCross.Forms.Presenters.Attributes;
using MyApp.Mobile.PageModels.Claims.Medical;
using MyApp.Mobile.Pages.Base;
using Xamarin.Forms;

namespace MyApp.Mobile.Pages.Claims.Medical
{
    [MvxContentPagePresentation(NoHistory = true)]
    public partial class ClaimConditionPage : BaseContentPage<ClaimConditionPageModel>
    {
        public ClaimConditionPage()
        {
            InitializeComponent();
        }

        protected override void OnAppearing()
        {
            if (BindingContext != null)
            {
                ClaimConditionPageModel model = (ClaimConditionPageModel)this.BindingContext.DataContext;

                model.QuestionAdded += Model_QuestionAdded;
            }

            base.OnAppearing();
        }

        protected override void OnDisappearing()
        {
            ClaimConditionPageModel model = (ClaimConditionPageModel)this.BindingContext.DataContext;

            model.QuestionAdded -= Model_QuestionAdded;
            base.OnDisappearing();
        }

        void Model_QuestionAdded(object sender, EventArgs e)
        {
            Device.BeginInvokeOnMainThread(async () =>
            {
                await QuestionScrollView.ScrollToAsync(0, QuestionScrollView.Content.Height, false);
            });

        }

    }
}

I've seen suggestions of adding a Task.Delay() to allow the UI to catch up - but this didn't work.

Note that this is only on iOS.

I note that there is this bug, but I don't think this is my problem. The ScrollView does scroll, but the display goes blank.

Versions
Xamarin.Forms 3.4.0.1029999

=== Visual Studio Community 2017 for Mac ===

Version 7.8.2 (build 1)
Installation UUID: 650b4c91-c7f5-4ee5-ad70-6f178f314906
GTK+ 2.24.23 (Raleigh theme)
Xamarin.Mac 5.0.0.0 ( / b40230c0)

Package version: 516000221

=== Mono Framework MDK ===

Runtime:
Mono 5.16.0.221 (2018-06/b63e5378e38) (64-bit)
Package version: 516000221

=== NuGet ===

Version: 4.8.0.5385

=== .NET Core ===

Runtime: /usr/local/share/dotnet/dotnet
Runtime Versions:
2.1.8
2.1.5
2.1.2
2.1.1
2.0.5
SDK: /usr/local/share/dotnet/sdk/2.1.504/Sdks
SDK Versions:
2.1.504
2.1.403
2.1.302
2.1.301
2.1.4
MSBuild SDKs: /Library/Frameworks/Mono.framework/Versions/5.16.0/lib/mono/msbuild/15.0/bin/Sdks

=== Xamarin.Profiler ===

Version: 1.6.4
Location: /Applications/Xamarin Profiler.app/Contents/MacOS/Xamarin Profiler

=== Updater ===

Version: 11

=== Apple Developer Tools ===

Xcode 10.1 (14460.46)
Build 10B61

=== Xamarin.Mac ===

Version: 5.2.1.15 (Visual Studio Community)
Hash: d60abd198
Branch:
Build date: 2019-02-01 12:23:30-0500

=== Xamarin.iOS ===

Version: 12.2.1.15 (Visual Studio Community)
Hash: d60abd198
Branch: d15-9
Build date: 2019-02-01 12:23:29-0500

=== Xamarin.Android ===

Version: 9.1.8.0 (Visual Studio Community)
Android SDK: /Users/jameslavery/Library/Developer/Xamarin/android-sdk-macosx
Supported Android versions:
2.3 (API level 10)
4.0.3 (API level 15)
4.1 (API level 16)
4.3 (API level 18)
4.4 (API level 19)
5.0 (API level 21)
5.1 (API level 22)
6.0 (API level 23)
7.0 (API level 24)
7.1 (API level 25)
8.0 (API level 26)
8.1 (API level 27)

SDK Tools Version: 26.1.1
SDK Platform Tools Version: 28.0.0
SDK Build Tools Version: 26.0.2

=== Microsoft Mobile OpenJDK ===

Java SDK: /Users/jameslavery/Library/Developer/Xamarin/jdk/microsoft_dist_openjdk_8.0.25
1.8.0-25
Android Designer EPL code available here:
https://github.com/xamarin/AndroidDesigner.EPL

=== Android Device Manager ===

Version: 7.8.1.0
Hash: 8924ea4a

=== Xamarin Inspector ===

Version: 1.4.3
Hash: db27525
Branch: 1.4-release
Build date: Mon, 09 Jul 2018 21:20:18 GMT
Client compatibility: 1

=== Build Information ===

Release ID: 708020001
Git revision: 13e0e5b7e85ffe742957e6f204bab5c06c644f0e
Build date: 2019-02-27 19:33:14+00
Build branch: release-7.8
Xamarin extensions: 23eaa7c9cdc9a3f55be7bb87b485a790ec82ef25

=== Operating System ===

Mac OS X 10.13.6
Darwin 17.7.0 Darwin Kernel Version 17.7.0
Fri Nov 2 20:43:16 PDT 2018
root:xnu-4570.71.17~1/RELEASE_X86_64 x86_64

=== Enabled user installed extensions ===

LiveXAML 1.3.31
MFractor 3.7.10
MvvmCross Template pack 2.0.1
NuGet Package Management Extensions 0.15
Template Creator 0.4
Redth's Addins 1.0.9
Internet of Things (IoT) development (Preview) 7.5

Ripple effect in StackLayout or Grid after click

$
0
0

How to achieve an effect of smooth change of background color in StackLayout or Grid after the click? If we create a button it has this effect out of the box - I showed that in an attached gif. The same is for ViewCell in ListView. It also has this ripple effect of changing background color after a click. But how to achieve that for StackLayout or Grid?

Viewing all 91519 articles
Browse latest View live


Latest Images

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