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

Xamarin.Forms Toolbar item with image not showing up on ios

$
0
0

Hi
I have a page with a toolbar item in xamarin forms. Image is stored in an "images" folder in PCL project and marked as embedded resource.
It works fine in android project but in ios I only get white circle.
If I put the same image in Image tag that works fine in ios.
Here's the code:

<ContentPage.ToolbarItems>
        <ToolbarItem IconImageSource="{local:EmbeddedImage MyProject.images.add.png}" Clicked="AddItem_Clicked"></ToolbarItem>
        <ToolbarItem Text="Export" Order="Secondary" Clicked="Export_Clicked"></ToolbarItem>
        <ToolbarItem Text="Import" Order="Secondary" Clicked="Import_Clicked"></ToolbarItem>
        <ToolbarItem Text="Backup" Order="Secondary" Clicked="Backup_Clicked"></ToolbarItem>
    </ContentPage.ToolbarItems>
    <StackLayout Padding="10, 10, 10, 10">
        <Image Source="{local:EmbeddedImage MyProject.images.add.png}"></Image>
    </StackLayout>


Maps MoveToLastRegionOnLayoutChange not working as expected

$
0
0

I have an issue with the Forms Maps.
When I drag the map and move away to a different screen, I see the map back to the last location set using "MoveToRegion" when I resume back the map screen. As per the documentation, setting MoveToLastRegionOnLayoutChange to False should prevent this behavior but it doesn't.

I didn't specifically test this property for screen rotation, but Renderer doesn't change on app sleep and resume.

Tried with below:

  • Xamarin Forms V16.6.000.1062
  • Android V8.1
  • Visual Studio 2019 V16.6.3

How to stop keyboard prematurely closing when Rg.Plugins.Popup closes in background in Xamarin Forms

$
0
0

Hi,

I'm currently working on a shopping list application. At the moment it's just a list view that is downloaded from an API Server. I'm working on a UndoPopup called ShoppingListPageUndoPage using Rg.Plugins.Popup that gives the user 5 seconds to undo the action before the popup closes itself. The problem I'm having is if the user opens another item in ItemDetailPage and uses the keyboard while the undo popup it open and counting down in the background, the keyboard will close itself when the popup in the background closes when the timer ends. This issue only affects Android, the keyboard stays open when ran on iOS.

Here's the code for the popup, ShoppingListPageUndoPage

ShoppingListPageUndoPopup.xaml

<?xml version="1.0" encoding="utf-8" ?>
<pages:PopupPage 

            xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup" 
            xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations;assembly=Rg.Plugins.Popup"
            xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:d="http://xamarin.com/schemas/2014/forms/design"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            mc:Ignorable="d"
            x:Class="ShoppingList.ShoppingListPageUndoPopup"
            HasSystemPadding="False"
            HasKeyboardOffset="True"
            KeyboardOffset="500"
            CloseWhenBackgroundIsClicked="False"
            BackgroundInputTransparent="True"
            BackgroundColor="Transparent">

    <pages:PopupPage.Animation>
        <animations:ScaleAnimation 
            PositionIn="Top"
            PositionOut="Center"
            ScaleIn="1.2"
            ScaleOut="0.8"
            DurationIn="200"
            DurationOut="100"
            EasingIn="SinOut"
            EasingOut="SinIn"
            HasBackgroundAnimation="True"/>
    </pages:PopupPage.Animation>

    <StackLayout  
        x:Name="PopupPageStackLayout"
        VerticalOptions="End"
        Padding="5,5,5,5"
        BackgroundColor="#17c200"
        Orientation="Horizontal"
        HeightRequest="45">

        <Label
            x:Name="InformationLabel"
            Text="#1"
            HorizontalOptions="StartAndExpand"
            FontSize="15"/>

        <Button 
               x:Name="undoButton"
               Text="(5) Undo"
               TextColor="Black"
               HorizontalOptions="EndAndExpand"
               Clicked="UndoButton_Clicked"/>

    </StackLayout>

</pages:PopupPage>

ShoppingListUndoPopup.xaml.cs

using Rg.Plugins.Popup.Extensions;
using Rg.Plugins.Popup.Pages;
using Rg.Plugins.Popup.Services;
using ShoppingList.Helpers;
using ShoppingList.Interfaces;
using ShoppingList.Model;
using System;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace ShoppingList
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class ShoppingListPageUndoPopup : PopupPage
    {
        public int currentPopupPosition;
        public int margin;
        public int popupOnSwitch;
        private bool keyboardOpen;
        Item ClosedItem;
        public ShoppingListPageUndoPopup(Item closedItem)
        {
            InitializeComponent();
            ClosedItem = closedItem;
            // Evaluating if margin needs adjusting to cater for removing white space:
            MessagingCenter.Subscribe<ShoppingListPageUndoPopup, string>(this, Constants.UNDO_POPUP_CLOSED, (sender, arg) =>
            {
                int closedPopupPosition = int.Parse(arg);
                // If the current popup position is greater then the closed popup position, repositioning will be required:
                if (currentPopupPosition > closedPopupPosition)
                {
                    // Re-Adjusting position:
                    currentPopupPosition -= 1;
                    Adjust_Margin(currentPopupPosition);
                }
            });

            MessagingCenter.Subscribe<App>((App)Application.Current, Constants.REQUEST_UNDO_POPUP_CLOSE, async (sender) =>
            {

                await Navigation.RemovePopupPageAsync(this);
            });

            int count = 4;
            Device.StartTimer(new TimeSpan(0, 0, 1), () =>
            {

                // Do something every 1 second:
                Device.BeginInvokeOnMainThread(() =>
                {
                    undoButton.Text = "(" + count.ToString() + ") Undo";
                    count--;
                });

                if (count == 0 & popupOnSwitch == 1)
                {
                    try
                    {
                        popupOnSwitch = 0;
                        Navigation.RemovePopupPageAsync(this);
                    }
                    catch (Exception e)
                    {
                        // Page removal failed due to already being removed (It's fine, this code runs after the popup is removed for some reason):
                    }
                    // Letting any other other instances of this page know this page is done and to re-evaluate their positions:
                    MessagingCenter.Send(this, Constants.UNDO_POPUP_CLOSED, currentPopupPosition.ToString());
                    return false;
                }
                else
                {
                    return true;
                }


            });

        }

        protected override void OnAppearing()
        {
            base.OnAppearing();
            var currentPopups = PopupNavigation.Instance.PopupStack;
            currentPopupPosition = currentPopups.Count;
            Adjust_Margin(currentPopupPosition);
            //InformationLabel.Text = currentPopupPosition.ToString();
            InformationLabel.Text = ClosedItem.Name + " deleted successfully.";
            popupOnSwitch = 1;

        }

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

            if (checkKeyboard())
            {
                MessagingCenter.Send<App>((App)Application.Current, Constants.REFOCUS_KEYBOARD);
            }
        }

        private async void UndoButton_Clicked(object sender, EventArgs e)
        {
            await Navigation.RemovePopupPageAsync(this);
            MessagingCenter.Send(this, Constants.UNDO_POPUP_CLOSED, currentPopupPosition.ToString());
            ClosedItem.Active = 1;
            popupOnSwitch = 0;
            await Item.Put(ClosedItem);
            MessagingCenter.Send<App>((App)Application.Current, Constants.POPUP_PAGE_FINISHED);
        }

        private void Adjust_Margin(int popupPosition)
        {
            margin = popupPosition * 45;
            PopupPageStackLayout.Margin = new Thickness(0, 0, 0, margin);
        }

        private bool checkKeyboard()
        {
            var keyboard = DependencyService.Get<IKeyboardService>();
            return keyboard.checkKeyboard();
        }
    }
}

ItemDetailPage.xaml

<pages:PopupPage
            xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup" 
            xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:d="http://xamarin.com/schemas/2014/forms/design"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations;assembly=Rg.Plugins.Popup"
            xmlns:local="clr-namespace:ShoppingList"
    mc:Ignorable="d"
            x:Class="ShoppingList.ItemDetailPage"
            HasSystemPadding="False"
            HasKeyboardOffset="True"
            KeyboardOffset="500">

    <pages:PopupPage.Animation>
        <animations:ScaleAnimation 
            PositionIn="Top"
            PositionOut="Center"
            ScaleIn="1.2"
            ScaleOut="0.8"
            DurationIn="200"
            DurationOut="100"
            EasingIn="SinOut"
            EasingOut="SinIn"
            HasBackgroundAnimation="True"/>
    </pages:PopupPage.Animation>

    <StackLayout
        VerticalOptions="End"
        Padding="5,5,5,5"
        BackgroundColor="#2196F3"
        Orientation="Vertical">

        <Label Text="Edit Item:"
               FontSize="30"
               TextColor="White"/>

        <StackLayout x:Name="EditItemStackLayout"
            Orientation="Horizontal"
            HorizontalOptions="FillAndExpand"
            Padding="5,0,5,0">

            <Entry 
               Text="{Binding Name, Mode=TwoWay}"
               x:Name="itemNameEntry"
               VerticalOptions="CenterAndExpand"
               HorizontalOptions="FillAndExpand"
               FontSize="20"
               TextColor="Black"
               ReturnCommand="{Binding UpdateItemCommand}"
               ReturnCommandParameter="{Binding Item}"/>

            <Label 
               Text="{Binding Id, Mode=TwoWay}"
               x:Name="itemIdLabel"
               VerticalOptions="CenterAndExpand"
               HorizontalOptions="FillAndExpand"
               FontSize="20"
               IsVisible="False"/>

            <Button 
                x:Name="updateButton"
                HorizontalOptions="End"
                ImageSource="forward.png"
                WidthRequest="50"
                HeightRequest="50"
                BackgroundColor="Transparent"
                Command="{Binding UpdateItemCommand}"
                CommandParameter="{Binding Item}"/>

        </StackLayout>

        <StackLayout
            Orientation="Horizontal"
            HorizontalOptions="Center"
            Padding="0,0,0,20">

            <Button Text="Delete"
                x:Name="deleteButton"
                TextColor="Black"
                Command="{Binding DeleteItemCommand}"
                CommandParameter="{Binding Item}"/>

            <Button Text="Cancel"
                x:Name="cancelButton"
                TextColor="Black"
                Command="{Binding ClosePopUpCommand}"/>

        </StackLayout>

    </StackLayout>

</pages:PopupPage>

ItemDetailPage.xaml.cs

using Plugin.Toast;
using Rg.Plugins.Popup.Extensions;
using Rg.Plugins.Popup.Pages;
using ShoppingList.Helpers;
using ShoppingList.Model;
using ShoppingList.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace ShoppingList
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class ItemDetailPage : PopupPage
    {
        Item SelectedItem;
        ItemDetailVM viewModel;
        public ItemDetailPage(Item selectedItem)
        {
            InitializeComponent();
            SelectedItem = selectedItem;
            viewModel = new ItemDetailVM();
            BindingContext = viewModel;

            // When below message is recieved, close page:
            MessagingCenter.Subscribe<App>((App)Application.Current, Constants.CLOSE_ITEM_DETAIL_PAGE, (sender) =>
            {
                Navigation.PopPopupAsync();
            });

            // When below message is recieved, refocus keyboard
            MessagingCenter.Subscribe<App>((App)Application.Current, Constants.REFOCUS_KEYBOARD, (sender) =>
            {
                Thread.Sleep(1000);
                refocus();
            });


        }

        protected override void OnAppearing()
        {
            // Requesting all open undo pops to close:
            try
            {
                //MessagingCenter.Send<App>((App)Application.Current, Constants.REQUEST_UNDO_POPUP_CLOSE);
            }
            catch
            {
                // If there's an issue, not to worry.
            }
            refocus();
        }

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

            MessagingCenter.Send<App>((App)Application.Current, Constants.POPUP_PAGE_FINISHED);
        }

        private void refocus()
        {
            itemNameEntry.Text = SelectedItem.Name;
            itemIdLabel.Text = SelectedItem.Id.ToString();
            itemNameEntry.Focus();
            int itemNameEntryLength = itemNameEntry.Text.Length;
            itemNameEntry.CursorPosition = itemNameEntryLength;
        }



    }
    public class CustomEntry : Entry
    {
    }

}

ItemDetailVM.cs

using Plugin.Toast;
using Rg.Plugins.Popup.Services;
using ShoppingList.Helpers;
using ShoppingList.Model;
using ShoppingList.ViewModel.Commands;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Http;
using System.Text;
using Xamarin.Forms;

namespace ShoppingList.ViewModel
{
    public class ItemDetailVM : INotifyPropertyChanged
    {

        public DeleteItemCommand DeleteItemCommand { get; set; }
        public ClosePopUpCommand ClosePopUpCommand { get; set; }
        public UpdateItemCommand UpdateItemCommand { get; set; }

        private Item item;
        public Item Item
        {
            get { return item; }
            set
            {
                item = value;
                OnPropertyChanged("Item");
            }
        }

        private int id;
        public int Id
        {
            get { return id; }
            set
            {
                id = value;
                Item = new Item()
                {
                    Id = this.Id,
                    Name = this.Name,
                    Active = this.Active
                };
                    OnPropertyChanged("Id");
            }
        }

        private string name;
        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                Item = new Item()
                {
                    Id = this.Id,
                    Name = this.Name,
                    Active = this.Active
                };
                OnPropertyChanged("Name");
            }
        }

        private int active;
        public int Active
        {
            get { return active; }
            set
            {
                id = value;
                Item = new Item()
                {
                    Id = this.Id,
                    Name = this.Name,
                    Active = this.Active
                };
                OnPropertyChanged("Active");
            }
        }

        public ItemDetailVM()
        {
            DeleteItemCommand = new DeleteItemCommand(this);
            UpdateItemCommand = new UpdateItemCommand(this);
            ClosePopUpCommand = new ClosePopUpCommand(this);
            Item = new Item();
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        // Methods go here:
        public async void updateItem(Item updatedItem)
        {
            updatedItem.Active = 1;
            HttpResponseMessage response = await Item.Put(updatedItem);

            if (response.StatusCode.ToString() == "OK")
            {
                CrossToastPopUp.Current.ShowToastSuccess(Strings.ITEM_UPDATED_SUCCESSFULLY);
                //Close popup page:
                MessagingCenter.Send<App>((App)Application.Current, Constants.CLOSE_ITEM_DETAIL_PAGE);
            } else
            {
                // Error occured updating item:

            }
        }

        public async void deleteItem(Item itemToDelete)
        {
            itemToDelete.Active = 0;
            HttpResponseMessage response = await Item.Put(itemToDelete);

            if (response.StatusCode.ToString() == "OK")
            {

                //Close popup page:
                MessagingCenter.Send<App>((App)Application.Current, Constants.CLOSE_ITEM_DETAIL_PAGE);

                // Letting previous page know item was deleted so user can undo if needed.
                await PopupNavigation.Instance.PushAsync(new ShoppingListPageUndoPopup(itemToDelete));
                //MessagingCenter.Send<ItemDetailVM,Item>(this,Constants.ITEM_DELETED, itemToDelete);
            }
            else
            {
                // Error occured deleting item:

            }
        }

        public void closePopup()
        {
            MessagingCenter.Send<App>((App)Application.Current, Constants.CLOSE_ITEM_DETAIL_PAGE);
        }


    }
}

If someone can point out where I'm going wrong here and how I can keep the keyboard open that would be appreciated.

How to repeat a local notification?

$
0
0

Hello everyone,

is it possible to repeat a local notification for both Android and iOS ? For example every day at 13:00 pm?

I am learning Xamarin.Forms, but I cannot find an example about this topic. Actually notifications are very commonly used. Why Xamarin.Forms does not provide some examples relating to this topic?

Look forward to your answers.
Thanks very much in advance!

Shell bottom Navigation How to implent to shell renderer for android and ios?

$
0
0

//BottomTabbedPageExtensions.cs

using Xamarin.Forms;

namespace SchedulingTool.Helpers
{
public class BottomTabbedPageExtensions
{
public static readonly BindableProperty TabColorProperty = BindableProperty.CreateAttached(
"TabColor",
typeof(Color),
typeof(BottomTabbedPageExtensions),
Color.Transparent);

    public static readonly BindableProperty BadgeCountProperty = BindableProperty.CreateAttached(
        "BadgeCount",
        typeof(int),
        typeof(BottomTabbedPageExtensions),
        0);

    public static readonly BindableProperty BadgeColorProperty = BindableProperty.CreateAttached(
        "BadgeColor",
        typeof(Color),
        typeof(BottomTabbedPageExtensions),
        Colors.OrangeColor);

    public static readonly BindableProperty IsTabVisibleProperty = BindableProperty.CreateAttached(
        "IsTabVisible", typeof(bool), typeof(BottomTabbedPageExtensions), true);

    public static void SetIsTabVisible(BindableObject bindable, bool visible)
    {
        bindable.SetValue(IsTabVisibleProperty, visible);
    }

    public static bool GetIsTabVisible(BindableObject bindable)
    {
        return (bool)bindable.GetValue(IsTabVisibleProperty);
    }

    public static void SetTabColor(BindableObject bindable, Color color)
    {
        bindable.SetValue(TabColorProperty, color);
    }

    public static Color GetTabColor(BindableObject bindable)
    {
        return (Color)bindable.GetValue(TabColorProperty);
    }

    public static void SetBadgeCount(BindableObject bindable, int badgeCount)
    {
        bindable.SetValue(BadgeCountProperty, badgeCount);
    }

    public static int GetBadgeCount(BindableObject bindable)
    {
        return (int)bindable.GetValue(BadgeCountProperty);
    }

    public static void IncreaseBadgeCountBy(BindableObject bindable, int increaseBy)
    {
        int currentValue = GetBadgeCount(bindable);
        if(currentValue == 0 && increaseBy < 0)
        {
            bindable.SetValue(BadgeCountProperty, 0);
        }

        if(increaseBy < 0 && (increaseBy > currentValue))
        {
            bindable.SetValue(BadgeCountProperty, 0);
        }

        bindable.SetValue(BadgeCountProperty, currentValue + increaseBy);
    }

    public static void SetBadgeColor(BindableObject bindable, Color color)
    {
        bindable.SetValue(BadgeColorProperty, color);
    }

    public static Color GetBadgeColor(BindableObject bindable)
    {
        return (Color)bindable.GetValue(BadgeColorProperty);
    }
}

}

//DroidBottomTabbedPageRenderer.cs

using System;
using System.Collections.Generic;
using System.Linq;

using Android.Content;
using Android.Support.Design.Widget;
using Android.Views;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android.AppCompat;
using View = Android.Views.View;
using AndroidRelativeLayout = Android.Widget.RelativeLayout;
using RelativeLayoutParams = Android.Widget.RelativeLayout.LayoutParams;

using Android.Support.Design.Internal;
using Xamarin.Forms.Platform.Android;
using System.ComponentModel;
using Android.Widget;
using Android.Graphics.Drawables;
using Android.Graphics.Drawables.Shapes;
using Android.Util;
using Android.Support.V4.View;

[assembly: ExportRenderer(typeof(ExtendedBottomTabbedPage), typeof(DroidBottomTabbedPageRenderer))]
namespace SchedulingTool.Droid.Renderers
{
public class DroidBottomTabbedPageRenderer : TabbedPageRenderer, BottomNavigationView.IOnNavigationItemReselectedListener
{
IDictionary<Page, string> _formsBadges;
List _androidBadges;

    bool _isShiftModeSet;
    int _l, _t, _r, _b, _width, _height, _tabsHeight;
    bool _firstTime;
    int _bottomBarHeight;
    Context _context;
    TabLayout _topBar;
    TabbedPage _tabbedPage;
    BottomNavigationView _bottomBar;
    AndroidRelativeLayout _container;
    RelativeLayoutParams _layoutParams;
    List<BottomNavigationItemView> _tabBarItems;
    ExtendedBottomTabbedPage _extendedTabbedPage;

    public DroidBottomTabbedPageRenderer(Context context) : base(context)
    {
        _context = context;
    }

    protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
    {
        base.OnElementChanged(e);

        if (e.NewElement != null)
        {
            _tabbedPage = e.NewElement;
            _extendedTabbedPage = (ExtendedBottomTabbedPage)_tabbedPage;
            _firstTime = true;
            _tabBarItems = new List<BottomNavigationItemView>();
            _androidBadges = new List<TextView>();

            var children = GetAllChildViews(ViewGroup);

            foreach (var bottomNavItemView in children)
            {
                if (bottomNavItemView is BottomNavigationItemView)
                {
                    var tab = (BottomNavigationItemView)bottomNavItemView;
                    _tabBarItems.Add(tab);
                    AddBadge(tab);
                }
            }
            if (children.SingleOrDefault(x => x is BottomNavigationView) is BottomNavigationView bottomNav)
            {
                _bottomBar = bottomNav;
                _bottomBar.SetOnNavigationItemReselectedListener(this);
            }
            if(children.SingleOrDefault(x => x is AndroidRelativeLayout) is AndroidRelativeLayout container)
            {
                _container = container;
            }
            if (children.SingleOrDefault(x => x is TabLayout) is TabLayout topNav)
            {
                _topBar = topNav;
            }

            SetTabBadges();
            AddPropertyChangedHandlersForPages();
        }
    }

    protected override void OnLayout(bool changed, int l, int t, int r, int b)
    {
        try
        {
            base.OnLayout(changed, l, t, r, b);

            _width = r - l;
            _height = b - t;
            _tabsHeight = Math.Min(_height, Math.Max(_bottomBar.MeasuredHeight, _bottomBar.MinimumHeight));

            _l = l;
            _t = t;
            _r = r;
            _b = b;

            if (!_isShiftModeSet)
            {
                _bottomBar.SetShiftMode(false, false);
                _isShiftModeSet = true;
            }
        }
        catch (Exception ex)
        {
            ExceptionHandler.LogException(this, nameof(OnLayout), ex);
        }
    }

    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);
        if (e.PropertyName == nameof(ExtendedBottomTabbedPage.BottomTabBarHidden))
        {
            HideTabbedPage();
        }
    }

    public async void OnNavigationItemReselected(IMenuItem item)
    {
        await _extendedTabbedPage.CurrentPage.Navigation.PopToRootAsync();
    }

    List<View> GetAllChildViews(View view)
    {
        if (!(view is ViewGroup group))
        {
            return new List<View> { view };
        }

        var result = new List<View>();

        for (int i = 0; i < group.ChildCount; i++)
        {
            var child = group.GetChildAt(i);

            var childList = new List<View> { child };
            childList.AddRange(GetAllChildViews(child));

            result.AddRange(childList);
        }

        return result.Distinct().ToList();
    }

    void AddPropertyChangedHandlersForPages()
    {
        foreach (var page in _extendedTabbedPage.Children)
        {
            page.PropertyChanged += OnPagePropertyChanged;
        }
    }

    void OnPagePropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == BottomTabbedPageExtensions.BadgeCountProperty.PropertyName)
        {
            var page = (Page)sender;
            UpdateBadgeForPage(page);
        }
    }

    void SetTabBadges()
    {
        var tabCount = _tabbedPage.Children.Count();
        _formsBadges = new Dictionary<Page, string>(tabCount);

        for (var i = 0; i < tabCount; i++)
        {
            var page = _tabbedPage.Children[i];
        }
    }

    void AddBadge(BottomNavigationItemView frame)
    {
        View badge = LayoutInflater.From(_context).Inflate(Resource.Layout.NotificationBadge, frame, false);
        frame.AddView(badge);
        TextView textViewBadge = (TextView)badge.FindViewById(Resource.Id.notifications_badge);

        var backgroundShape = CreateBackgroundShape();
        backgroundShape.Paint.Color = Colors.OrangeColor.ToAndroid();
        ViewCompat.SetBackground(textViewBadge, backgroundShape);

        _androidBadges.Add(textViewBadge);
    }

    void UpdateBadgeForPage(Page page)
    {
        if (_tabbedPage == null) return;

        var pageIndex = _tabbedPage.Children.IndexOf(page);
        var badgeCount = BottomTabbedPageExtensions.GetBadgeCount(page);

        if (!_formsBadges.ContainsKey(page))
        {
            _formsBadges.Add(page, page.Title);
        }

        var badge = _androidBadges[pageIndex];
        var tab = _tabBarItems[pageIndex];

        if (badgeCount <= 0)
        {
            badge.Visibility = ViewStates.Gone;
            return;
        }

        badge.Visibility = ViewStates.Visible;
        badge.Text = badgeCount > 99 ? "99+" : badgeCount.ToString();

    }

    void HideTabbedPage()
    {
        if (_firstTime)
        {
            _layoutParams = (RelativeLayoutParams)_bottomBar.LayoutParameters;
            _l = _layoutParams.LeftMargin;
            _t = _layoutParams.TopMargin;
            _r = _layoutParams.RightMargin;
            _b = _layoutParams.BottomMargin;
            _bottomBarHeight = _layoutParams.Height;
            _firstTime = false;
        }

        if (_extendedTabbedPage.BottomTabBarHidden)
        {
            _layoutParams.Height = 0;
            _bottomBar.LayoutParameters = _layoutParams;
            //_topBar.Visibility = ViewStates.Gone;
            //_bottomBar.LayoutParameters = new global::Android.Widget.RelativeLayout.LayoutParams(0,0);
            //_container.Invalidate();
            //_bottomBar.Visibility = ViewStates.Gone;
            //Measure(MeasureSpecFactory.MakeMeasureSpec(_width, MeasureSpecMode.Exactly), MeasureSpecFactory.MakeMeasureSpec(_tabsHeight, MeasureSpecMode.Exactly));
            //Layout(_l, _t, _r, _b);
        }
        else
        {
            _layoutParams.Height = _bottomBarHeight;
            _bottomBar.LayoutParameters = _layoutParams;
            //_topBar.Visibility = ViewStates.Visible;
            //_container.Invalidate();
            //_bottomBar.Visibility = ViewStates.Visible;
            //Measure(MeasureSpecFactory.MakeMeasureSpec(_width, MeasureSpecMode.Exactly), MeasureSpecFactory.MakeMeasureSpec(_tabsHeight, MeasureSpecMode.Exactly));
            //Layout(_l, _t, _r, _b);
        }
    }

    ShapeDrawable CreateBackgroundShape()
    {
        var radius = DpToPixels(12);
        var outerR = new float[] { radius, radius, radius, radius, radius, radius, radius, radius };
        return new ShapeDrawable(new RoundRectShape(outerR, null, null));
    }

    int DpToPixels(float dip)
    {
        return (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, dip, Resources.DisplayMetrics);
    }

}

public static class AndroidHelpers
{
    public static void SetShiftMode(this BottomNavigationView bottomNavigationView, bool enableShiftMode, bool enableItemShiftMode)
    {
        try
        {
            var menuView = bottomNavigationView.GetChildAt(0) as BottomNavigationMenuView;
            if (menuView == null)
            {
                System.Diagnostics.Debug.WriteLine("Unable to find BottomNavigationMenuView");
                return;
            }


            var shiftMode = menuView.Class.GetDeclaredField("mShiftingMode");

            shiftMode.Accessible = true;
            shiftMode.SetBoolean(menuView, enableShiftMode);
            shiftMode.Accessible = false;
            shiftMode.Dispose();


            for (int i = 0; i < menuView.ChildCount; i++)
            {
                var item = menuView.GetChildAt(i) as BottomNavigationItemView;
                if (item == null)
                    continue;

                item.SetShiftingMode(enableItemShiftMode);
                item.SetChecked(item.ItemData.IsChecked);

            }

            menuView.UpdateMenuView();
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"Unable to set shift mode: {ex}");
        }
    }
}

}

//ExtendedBottomTabbedPage.cs

using Xamarin.Forms;

namespace SchedulingTool.Renderers
{
public class ExtendedBottomTabbedPage : TabbedPage
{
#region Properties & Commands

    public static readonly BindableProperty TabBarHiddenProperty =
        BindableProperty.Create(nameof(BottomTabBarHidden), typeof(bool), typeof(ExtendedBottomTabbedPage), false);

    public bool BottomTabBarHidden
    {
        get { return (bool)GetValue(TabBarHiddenProperty); }
        set { SetValue(TabBarHiddenProperty, value); }
    }

    public enum BarThemeTypes { Light, DarkWithAlpha, DarkWithoutAlpha }

    public BarThemeTypes BarTheme { get; set; }

    public bool FixedMode { get; set; }

    #endregion

    #region Methods

    public void RaiseCurrentPageChanged()
    {
        OnCurrentPageChanged();
    }

    #endregion
}

}

Cross-platform UIPopoverViewController??

$
0
0

Is there any support in Xamarin Forms for something like UIPopoverViewController? I would like to display a popup (not full screen) on larger screens that contains a NavigationPage or ContentPage. I can probably create something myself but though maybe I was missing something.

Sudden app crash MVVM

$
0
0

Why on this line - Page page = Activator.CreateInstance(pageType) as Page; app is crash? I make mvvm by guide from microsoft.

I haven't changed or touched anything on the page that I open at startup. Changed only the service that is not used on the same page.

Page type:

Lookout App Defense SDK Integration

$
0
0

Hi Everyone,

I would like integrate the Mobile App security "Lookout App Defence SDK" in the Xamarin.Forms mobile app.

But it is available for the Native Android & iOS and code updated in gradle files.

Is it possible to convert Native Languages .gradle files code into the Xamarin.Forms App?

Any ideas?

Thanks & Regards,

Ashwin C


How to Load cache Image in offline in xamarin forms?

$
0
0

The issue occurs in all 3 platforms:

I am downloading an image and stored in the cache(default option for an image source "CachingEnabled = true"), and I have set the time span to 1 day.

On Loading, the page in offline the image is not displayed. whereas if I open the page in online it seems the image is downloaded and shown

Initially, I am downloading and saving as follows

webImage.Source = new UriImageSource
{
Uri = new Uri("Some Http image"),
CachingEnabled = true,
CacheValidity=new TimeSpan(1,0,0,0)
};

In the new page, I am using the following to show the image

newImage.Source = new UriImageSource
{
Uri = new Uri("Some Http image"),
}

In Offline, An empty page has displayed the image is not loaded. I have a question is whether the image is cached or not.

My question here is ** Has the image is cached? If so how to load the cached image in offline.**

How do I change the default audio language in xamarin forms

$
0
0

How do I change the default audio language in movie(hindi to english or English to Hindi)
In xamarin forms , video player

How to stop YouTube video after click back button in webview in xamarin forms

$
0
0

How to stop YouTube video after click back button in webview in xamarin forms

I have created custom webview and I want to Stop YouTube video after click close button
But video are playing in background.....
....

Image Button on click change image but not during scroll.

$
0
0

Good Day,

I was hoping someone could possible assist me.

I was using the Pressed trigger to change an image buttons source but since I have added a scroll view now whenever I "Press" to scroll up or down the image button(s) change to their pressed image (and don't change back since i don't have a trigger to change the image to normal should it not be clicked, i i tried Unpressed but it doesn't seem to trigger when scrolled).
I am currently loading a new page on the clicked event.
I was hoping that after the button has lost focus it could return to its normal image state. E.G if i Press on Button A (Button A turns Grey) and scroll up or down then once i release my finger Button A would return back to its normal state.

I have 24 buttons and was looking at creating a bool that is set to true when a button is pressed then on the "Scrolled" trigger i would check if the bool is true and if (true) set the button back to its normal state but this looks kinda buggy as it changes as soon as you start scrolling.

I also looked at using the Focus and Unfocused triggers but they didn't seem to do anything.

XForms iOS project not building with Prism

$
0
0

Hi guys, I have an iOS app I have built and it keeps crashing at app initialisation, I created a new xforms prism iOS app to make sure I did everythin right and that the packages installed were also correct, and they were. Somebody please help me out.

Additional Information
*Prism.DryIoc.Forms v7.2.0.1367 installed in iOS and .NET Standard project
*Prism.Core and Prism.Forms installed in .NET standard project
*App.xaml.cs is the same in both projects (mine and the one created from Prism Template Pack extension which works)

The exception is DryIoc.Container Exception
Message : "Undefined Method "GetDefault" in Type Dry.Ioc.ReflectionTools"
Source : "DryIoc"

The code breaks at `public App(IPlatformInitializer initializer) : base(initializer) {}

App.xaml.cs (for non working solution)

namespace TestApp
{
    public partial class App
    {
        public App() : this(null) { }
        public App(IPlatformInitializer initializer) : base(initializer) { }
        protected override async void OnInitialized()
        {
            InitializeComponent();

            //Navigation code
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
        }

        protected override void OnStart()
        {
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
}

iOS works in Debug but mono crashes at splash screen in Release / AppStore

$
0
0

Sorry to bother you guys, but I've been struggling with this for several days now and I'm out of ideas!

I've been testing an app via TestFlight for a while, but the 90 day expired and I had to upload a new version to keep the beta testers alive.

What changed?

  • Code wise, nothing!
  • VS version updated
  • Xamarin updated
  • Some Nugets updated.

It all still runs (on all my devices) in debug mode, but in release mode, ad-hoc and AppStore mode is crashes at the splash screen.

I've tried all linker options but it makes no difference. I've tried to strip out as much code as possible but it happens with even a bare bones amount of code running. It looks like it's crashing on a mono invoke but I am quite willing to be corrected there.

Help!

The console shows this:

Launched application 'xxxappname' on 'iPad Air 2 Device' with pid 1175
2020-07-16 14:46:02.099 xxxappname'[1175:596388] error: * Assertion at /Users/builder/jenkins/workspace/archive-mono/2020-02/ios/release/mono/mini/mini-trampolines.c:1494, condition `invoke' not met

=================================================================

Native Crash Reporting

Got a abrt while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries

used by your application.

=================================================================

Native stacktrace:

0x102d92cc8 - /private/var/containers/Bundle/Application/C90B8695-455C-4C99-8B3C-8537AA5ABB65/xxxappname.iOS.app/xxxappname.iOS : 
0x102d89964 - /private/var/containers/Bundle/Application/C90B8695-455C-4C99-8B3C-8537AA5ABB65/xxxappname.iOS.app/xxxappname.iOS : 
0x102d92214 - /private/var/containers/Bundle/Application/C90B8695-455C-4C99-8B3C-8537AA5ABB65/xxxappname.iOS.app/xxxappname.iOS : 
0x19434b894 - /usr/lib/system/libsystem_platform.dylib : <redacted>
0x1943501e8 - /usr/lib/system/libsystem_pthread.dylib : <redacted>
0x1942a3934 - /usr/lib/system/libsystem_c.dylib : abort
0x102eced50 - /private/var/containers/Bundle/Application/C90B8695-455C-4C99-8B3C-8537AA5ABB65/xxxappname.iOS.app/xxxappname.iOS : xamarin_find_protocol_wrapper_type
0x102ec90a4 - /private/var/containers/Bundle/Application/C90B8695-455C-4C99-8B3C-8537AA5ABB65/xxxappname.iOS.app/xxxappname.iOS : 
0x102ec912c - /private/var/containers/Bundle/Application/C90B8695-455C-4C99-8B3C-8537AA5ABB65/xxxappname.iOS.app/xxxappname.iOS : 
0x102ec915c - /private/var/containers/Bundle/Application/C90B8695-455C-4C99-8B3C-8537AA5ABB65/xxxappname.iOS.app/xxxappname.iOS : 
0x102d9d4f0 - /private/var/containers/Bundle/Application/C90B8695-455C-4C99-8B3C-8537AA5ABB65/xxxappname.iOS.app/xxxappname.iOS : 
0x102d947ac - /private/var/containers/Bundle/Application/C90B8695-455C-4C99-8B3C-8537AA5ABB65/xxxappname.iOS.app/xxxappname.iOS : 
0x102d74c5c - /private/var/containers/Bundle/Application/C90B8695-455C-4C99-8B3C-8537AA5ABB65/xxxappname.iOS.app/xxxappname.iOS : 
0x102d75cec - /private/var/containers/Bundle/Application/C90B8695-455C-4C99-8B3C-8537AA5ABB65/xxxappname.iOS.app/xxxappname.iOS : 
0x102d75528 - /private/var/containers/Bundle/Application/C90B8695-455C-4C99-8B3C-8537AA5ABB65/xxxappname.iOS.app/xxxappname.iOS : 
0x102d94e3c - /private/var/containers/Bundle/Application/C90B8695-455C-4C99-8B3C-8537AA5ABB65/xxxappname.iOS.app/xxxappname.iOS : 
0x102d995f0 - /private/var/containers/Bundle/Application/C90B8695-455C-4C99-8B3C-8537AA5ABB65/xxxappname.iOS.app/xxxappname.iOS : 
0x102e32b30 - /private/var/containers/Bundle/Application/C90B8695-455C-4C99-8B3C-8537AA5ABB65/xxxappname.iOS.app/xxxappname.iOS : 
0x102e34738 - /private/var/containers/Bundle/Application/C90B8695-455C-4C99-8B3C-8537AA5ABB65/xxxappname.iOS.app/xxxappname.iOS : 
0x102ecefe4 - /private/var/containers/Bundle/Application/C90B8695-455C-4C99-8B3C-8537AA5ABB65/xxxappname.iOS.app/xxxappname.iOS : xamarin_find_protocol_wrapper_type
0x102ed5770 - /private/var/containers/Bundle/Application/C90B8695-455C-4C99-8B3C-8537AA5ABB65/xxxappname.iOS.app/xxxappname.iOS : xamarin_release_block_on_main_thread
0x100717e98 - /private/var/containers/Bundle/Application/C90B8695-455C-4C99-8B3C-8537AA5ABB65/xxxappname.iOS.app/xxxappname.iOS : 
0x1944428f0 - /usr/lib/system/libdyld.dylib : <redacted>

=================================================================

Basic Fault Address Reporting

Memory around native instruction pointer (0x194437d88):0x194437d78 c0 03 5f d6 c0 03 5f d6 10 29 80 d2 01 10 00 d4 .......)......
0x194437d88 e3 00 00 54 fd 7b bf a9 fd 03 00 91 4f 7b ff 97 ...T.{......O{..
0x194437d98 bf 03 00 91 fd 7b c1 a8 c0 03 5f d6 c0 03 5f d6 .....{........
0x194437da8 90 29 80 d2 01 10 00 d4 e3 00 00 54 fd 7b bf a9 .).........T.{..

=================================================================

Managed Stacktrace:

=================================================================
Application 'xxxappname' terminated.

UWP Setting Custom Icon in MapRenderer

$
0
0

I'm trying to draw text on a custom image and set it as a map icon. I've done this with Android and IoS; however, in UWP I've encountered some issues.
The UWP renderer mapIcon.Image requires a uri, stream or file. I've tried several different ways. The following is attempting to return a stream:

public async Task WriteTextOnImage(string uri, string text, Windows.UI.Color color)
{
Uri uriSource = new Uri(uri);
using (CanvasBitmap bitmap = await CanvasBitmap.LoadAsync(CanvasDevice.GetSharedDevice(), uriSource).AsTask().ConfigureAwait(false))
using (CanvasRenderTarget target = new CanvasRenderTarget(CanvasDevice.GetSharedDevice(), (float)bitmap.Size.Width, (float)bitmap.Size.Height, bitmap.Dpi))
{
using (var ds = target.CreateDrawingSession())
{
ds.Clear(Colors.White);
ds.DrawImage(bitmap);
ds.DrawText(text, new System.Numerics.Vector2(150, 150), color);
}
byte[] arr = target.GetPixelBytes();
MemoryStream stream = new MemoryStream(arr);
return stream.AsRandomAccessStream();
}
}

The image is not appearing. I'd appreciate any ideas on this issue.


Carouselview not showing in iOS (Xamarin.Forms - 3.6.0.709228)

$
0
0

I am using xamarin.forms 3.6.0.709228. and I am trying to implement CarousleView which works fine in android but not showing in iOS. Is there any bug with Xamarin.Forms(3.6.0.709228) version ? or Is there any workaround to use CarouselView with Xamarin.Forms(3.6.0.709228) ?

Xamarin forms: Epubreader: System.AggregateException: 'One or more errors occurred

$
0
0

I am using epubreader (vers-one) NuGet package for parsing .epub files.

My Code:

string fileName = "SampleEPUB.epub";
var assembly = typeof(MainPage).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{fileName}");
EpubBook epubBook = EpubReader.ReadBook(stream);
foreach (EpubNavigationItem chapter in epubBook.Navigation)
{
    chapterDetails.Add(new ChapterDetails() { title = chapter.Title, htmlData = chapter.HtmlContentFile?.Content, subChapters = chapter.NestedItems });
}

For testing purposes, I have added the epub files on the project and parse the chapters like above. I need to change this implementation.

I am able to get the epub file links stored in our database. Now I need to parse the chapters of epub from the link. But when I use the link as the fileName in the above code I am getting the below exception:

System.AggregateException: 'One or more errors occurred. (Value cannot be null.Parameter name: stream)'

How can I solve this issue? One sample link is here. I have added a sample project here having .epub file links for the reference (epub file links are commented in the sample).

FlyoutItem dynamically loaded

$
0
0

Hello,
Is there any way to bind the items displayed in the shell FlyoutItem? In my app i want to enable to user too add devices after which these devices will be displayed in the Flyout.
Thank you

Simple way to poll server from Xamarin.Forms client

$
0
0

Hi there
I have to implement a polling code to send a device App status to a server (I use WCF) and get a command from the server to be executed (if at all).
It polls each, say, 10 seconds regardless whether the app commands the screen or the device is hibernating (I mean it screen gets black while it left untouched for a time).
Can I just attach my PollingTimerClass to the Application.Current and start it in OnStart() event handler?
Again, it must poll when:
1. Application is active
2. Application is not active. It is pushed by another application on the screen
3. Device is a black screen, but it is not off

Thanks.

Xamarin TabbedPage Issue

$
0
0

Hello everyone!
am having a major issue with xamarin tabbed page
There is one tabbed page in my xamarin project called TodayTabbedPage so by default in android, Tabs will be shown at the top side so I write following code in tabbed page XAML file to place them at bottom
xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
android:TabbedPage.ToolbarPlacement="Bottom"
android:TabbedPage.BarItemColor="#262626"
android:TabbedPage.BarSelectedItemColor="#9900CC"
So It perfectly showing all tabs at the bottom
But whenever am calling another tabbed page instead of TodayTabbedPage the bottom tab line still shows
Hope this information is enough please help!!!

Viewing all 79144 articles
Browse latest View live


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