Override navbar back button click on Xamarin.Forms - xamarin

Is there any way to show an alert msg before clicking navbar back icon & exiting the page.
I've tried this solution but it's not working.

If you want to capture the back button click the Action Bar in android platform, you can try to override the OnOptionsItemSelected() in the MainActivity class, which allows us to capture the navigation bar’s back button click.
Please follow up the following steps:
1.create a base contentpage CoolContentPage.cs
public class CoolContentPage: ContentPage
{
/// <summary>
/// Gets or Sets the Back button click overriden custom action
/// </summary>
public Action CustomBackButtonAction { get; set; }
public static readonly BindableProperty EnableBackButtonOverrideProperty =
BindableProperty.Create(
nameof(EnableBackButtonOverride),
typeof(bool),
typeof(CoolContentPage),
false);
/// <summary>
/// Gets or Sets Custom Back button overriding state
/// </summary>
public bool EnableBackButtonOverride
{
get
{
return (bool)GetValue(EnableBackButtonOverrideProperty);
}
set
{
SetValue(EnableBackButtonOverrideProperty, value);
}
}
}
2.override the OnOptionsItemSelected() event in MainActivity class in order to capture the nav bar back button click in Android for Xamarin Forms.
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
//TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
AndroidX.AppCompat.Widget.Toolbar toolbar
= this.FindViewById<AndroidX.AppCompat.Widget.Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
// check if the current item id
// is equals to the back button id
if (item.ItemId == 16908332) // xam forms nav bar back button id
{
// retrieve the current xamarin
// forms page instance
var currentpage = (CoolContentPage)Xamarin.Forms.Application.Current.
MainPage.Navigation.NavigationStack.LastOrDefault();
// check if the page has subscribed to the custom back button event
if (currentpage?.CustomBackButtonAction != null)
{
// invoke the Custom back button action
currentpage?.CustomBackButtonAction.Invoke();
// and disable the default back button action
return false;
}
// if its not subscribed then go ahead
// with the default back button action
return base.OnOptionsItemSelected(item);
}
else
{
// since its not the back button
//click, pass the event to the base
return base.OnOptionsItemSelected(item);
}
}
public override void OnBackPressed()
{
// this is really not necessary, but in Android user has both Nav bar back button
// and physical back button, so its safe to cover the both events
var currentpage = (CoolContentPage)Xamarin.Forms.Application.Current.
MainPage.Navigation.NavigationStack.LastOrDefault();
if (currentpage?.CustomBackButtonAction != null)
{
currentpage?.CustomBackButtonAction.Invoke();
}
else
{
base.OnBackPressed();
}
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Here, we need to create Toolbar.xml in folder layout
Toolbar.xml
<androidx.appcompat.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
3.In xamarin forms,we can use CoolContentPage we created above as a XAML page in Xamarin Forms solution:
MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<xfbackbtnapp:CoolContentPage xmlns:xfbackbtnapp="clr-namespace:XFBackBtnApp"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XFBackBtnApp.MainPage"
EnableBackButtonOverride="False"
Title="Home Page"
BackgroundColor="#00bfff"
>
<StackLayout
Spacing="20"
Padding="20,10,20,10"
VerticalOptions="Center"
HorizontalOptions="Center" >
<Label Text="Welcome to Navigation Bar Back button Click overriding in Xamarin Forms!"
FontSize="20"
HorizontalTextAlignment="Center"
TextColor="White"/>
<Button Text="Open Next Page" FontSize="15" BackgroundColor="White" Clicked="OpenPageButton_OnClicked"></Button>
</StackLayout>
</xfbackbtnapp:CoolContentPage>
MainPage.xaml.cs
public partial class MainPage : CoolContentPage
{
public MainPage()
{
InitializeComponent();
}
private void OpenPageButton_OnClicked(object sender, EventArgs e)
{
Navigation.PushAsync(new Page1());
}
}
Page1.xaml
<?xml version="1.0" encoding="utf-8" ?>
<xfbackbtnapp:CoolContentPage xmlns:xfbackbtnapp="clr-namespace:XFBackBtnApp"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
EnableBackButtonOverride="False"
BackgroundColor="#00bfff"
Title="Page 1"
x:Class="XFBackBtnApp.Page1">
<ContentPage.Content>
<StackLayout
Spacing="20"
Padding="20,10,20,10"
VerticalOptions="Center"
HorizontalOptions="Center" >
<Label Text="Ok, this is just a normal Page! Click next Page to see the Navigation Bar Back button click overridden behavior..."
FontSize="20"
HorizontalTextAlignment="Center"
TextColor="White"/>
<Button Text="Open Next Page" FontSize="15" BackgroundColor="White" Clicked="OpenPageButton_OnClicked"></Button>
</StackLayout>
</ContentPage.Content>
</xfbackbtnapp:CoolContentPage>
Page1.xaml.cs
public partial class Page1 : CoolContentPage
{
public Page1()
{
InitializeComponent();
}
private void OpenPageButton_OnClicked(object sender, EventArgs e)
{
Navigation.PushAsync(new Page2());
}
}
Page2.xaml
<?xml version="1.0" encoding="utf-8" ?>
<xfbackbtnapp:CoolContentPage xmlns:xfbackbtnapp="clr-namespace:XFBackBtnApp"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XFBackBtnApp.Page2"
EnableBackButtonOverride="True"
BackgroundColor="#00bfff"
Title="Page 2"
>
<ContentPage.Content>
<StackLayout
Spacing="20"
Padding="20,10,20,10"
VerticalOptions="Center"
HorizontalOptions="Center" >
<Label Text="This is the cool page, which has the Navigation Bar Back button click overriden. How go ahead and click that Back button! ;)"
FontSize="20"
HorizontalTextAlignment="Center"
TextColor="White"/>
</StackLayout>
</ContentPage.Content>
</xfbackbtnapp:CoolContentPage>
Page2.xaml.cs
public partial class Page2 : CoolContentPage
{
public Page2()
{
InitializeComponent();
if (EnableBackButtonOverride)
{
this.CustomBackButtonAction = async () =>
{
var result = await this.DisplayAlert(null,
"Hey wait now! are you sure " +
"you want to go back?",
"Yes go back", "Nope");
if (result)
{
await Navigation.PopAsync(true);
}
};
}
}
}
Note:
1.Here,I added property EnableBackButtonOverride="True" to the root of Page2.xaml, then if we can press the back button of the Toolbar on the top of the page or press the soft back button of our Phone, a DisplayAlert will pop up.
2.If you want to achieve this function in Ios,you can check article Override Navigation Bar back button click in Xamarin Forms.

Related

How to Trigger event Cancel Button on SearchBar Xamarin Form

Xamarin Form View Model can trigger the onTextChange Event for Searchbar but there is no Event handler for OnCancelButtonClicked.
What I want:
An Event should be Triggered whenever Cancel/Close Button is clicked as below.
You can get Searchbar CloseButton event in SearchBar custom render, but I think it is not useful for your goal.
I suggest you can click search icon to refresh data source. I don one sample using Searchbar and ListView, you can take a look:
[assembly: ExportRenderer(typeof(SearchBar), typeof(CustomSearchBarRenderer))]
namespace FormsSample.Droid
{
public class CustomSearchBarRenderer: SearchBarRenderer
{
public CustomSearchBarRenderer(Context context):base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
{
base.OnElementChanged(e);
if (Control != null)
{
var searchView = Control;
searchView.Iconified = true;
searchView.SetIconifiedByDefault(false);
int searchCloseButtonId = Context.Resources.GetIdentifier("android:id/search_close_btn", null, null);
// search close button icon, you can add event for closeIcon.click.
var closeIcon = searchView.FindViewById(searchCloseButtonId);
int searchViewSearchButtonId = Control.Resources.GetIdentifier("android:id/search_mag_icon", null, null);
var searchIcon = searchView.FindViewById(searchViewSearchButtonId);
searchIcon.Click += SearchIcon_Click;
}
}
private void SearchIcon_Click(object sender, EventArgs e)
{
Element.OnSearchButtonPressed();
}
}
}
<StackLayout>
<SearchBar
x:Name="searchBar"
HorizontalOptions="Fill"
Placeholder="Search fruits..."
SearchButtonPressed="OnSearchButtonPressed"
VerticalOptions="CenterAndExpand" />
<Label
HorizontalOptions="Fill"
Text="Enter a search term and press enter or click the magnifying glass to perform a search."
VerticalOptions="CenterAndExpand" />
<ListView
x:Name="searchResults"
HorizontalOptions="Fill"
VerticalOptions="CenterAndExpand" />
</StackLayout>
public partial class Page23 : ContentPage
{
public Page23()
{
InitializeComponent();
searchResults.ItemsSource = DataService.Fruits;
}
private void OnSearchButtonPressed(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(searchBar.Text))
{
searchResults.ItemsSource = DataService.Fruits;
}
else
{
searchResults.ItemsSource = DataService.GetSearchResults(searchBar.Text);
}
}
}
You can click search closebutton to move text in SearchBar firstly, then click SearchButton to refresh data for listView.

Do A on tabbedpage children button click, do B when the same button is pressed for x seconds

I have spent my recent hours on researching on how to make this possible
I have a bottom tabbed page with a home button. What I want to achieve is, when button is pressed for x seconds, a new page shall be opened. How should the custom renderer for the tabbed page look like?
I already have one custom renderer for the tabbed page that makes sure that the home page button is a floating action button. The custom renderer for the home page button:
[assembly: ExportRenderer(typeof(NavigationBar), typeof(CustomTabbedRenderer))]
namespace MysteryLocation.Droid
{
public class CustomTabbedRenderer : TabbedPageRenderer
{
Context context;
public CustomTabbedRenderer(Context context) : base(context)
{
this.context = context;
}
protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
{
base.OnElementChanged(e);
if (e.OldElement == null && e.NewElement != null)
{
for (int i = 0; i <= this.ViewGroup.ChildCount - 1; i++)
{
var childView = this.ViewGroup.GetChildAt(i);
if (childView is ViewGroup viewGroup)
{
((ViewGroup)childView).SetClipChildren(false);
for (int j = 0; j <= viewGroup.ChildCount - 1; j++)
{
var childRelativeLayoutView = viewGroup.GetChildAt(j);
if (childRelativeLayoutView is BottomNavigationView bottomView)
{
FloatingActionButton button = new FloatingActionButton(context);
BottomNavigationView.LayoutParams parameters = new BottomNavigationView.LayoutParams(150, 150);
parameters.Gravity = GravityFlags.CenterHorizontal;
Drawable d = Resources.GetDrawable(Resource.Drawable.image);
button.SetScaleType(Android.Widget.ImageView.ScaleType.Center);
button.SetImageDrawable(d);
button.LayoutParameters = parameters;
bottomView.AddView(button);
}
}
}
}
}
}
}
}
==========
EDIT
==========
In my customtabbedrenderer I've added button.LongClick += Button_LongClick and button.Click += Button_Click with the methods
private void Button_LongClick(object sender, EventArgs e)
{
//open a page through pushasync
}
private void Button_Click(object sender, EventArgs e)
{
//navigate to the page as usual, as it does when there's no
"button.Click" specified in the custom renderer
}
Any ideas on how the code should look like in the given methods?
=========
EDIT 2
=========
I have solved on long click, a new page is being opened through
button.LongClick += (object sender, LongClickEventArgs args) =>
{
Application.Current.MainPage.Navigation.PushModalAsync(new NavigationPage(new Pass()));
};
The app works both on click and on long click now. The remaining problem is, how can I allow the same button to navigate to the page that it is supposed to when only doing a simple click? It navigates to that page when there's no "button.Click += Button_Click" and "button.LongClick += Button_Click1". But as soon as I add a longclick event, the button stops working on click.
==========================
SOLVED
==========================
Added Element.CurrentPage = Element.Children[2] in the method Button_Click method, simple as that.
Longpress may be problematic in XF. For one of my applications I used a double tap:
<?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:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
xmlns:CustomCtrls ="clr-namespace:D4503.CustomControls"
xmlns:Views="clr-namespace:D4503.Views"
x:Class="D4503.Pages.MainPage"
BackgroundColor="{StaticResource ScreenBackColor}"
ios:Page.UseSafeArea="true">
<ContentPage.Content>
<StackLayout>
<Image Grid.Row="1" Grid.Column="0" x:Name="btnRed" Style="{StaticResource ColorButtonImage}" Source="stoplight_red.png"
Aspect="AspectFit">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="Red_Button_Tapped"/>
<TapGestureRecognizer Tapped="Red_Button_Tapped_Double" NumberOfTapsRequired="2" />
</Image.GestureRecognizers>
</Image>
</StackLayout>
</ContentPage.Content>
</ContentPage>

How to show Navigationbar 'TitleView' Common for all pages

I have added TitleView in MainPage to show on Navigationbar but it shows only for MainPage when I navigate to some other page Navigationbar displaying empty.
Below code I have in MainPage.xaml file
<NavigationPage.TitleView>
<RelativeLayout HorizontalOptions="Fill"
<Image Source="bell.png" HeightRequest="25" WidthRequest="25" x:Name="imgBell"
RelativeLayout.YConstraint="{ConstraintExpression
Type=RelativeToParent,
Property=Height,
Factor=0.018,Constant=10}">
<Image.GestureRecognizers>
<TapGestureRecognizer Command="{Binding GetStaffAnnouncementCommand}"></TapGestureRecognizer>
</Image.GestureRecognizers>
</Image>
<Label FontSize="10" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" BackgroundColor="Transparent" Text="2" TextColor="Red"
HeightRequest="22" WidthRequest="23" x:Name="labelText">
</Frame>
</RelativeLayout>
</NavigationPage.TitleView>
When I click on bell icon and move to second page TitleView not displaying at all
How can I display TitleView common for all pages?
I wrote a demo about your needs.
There is GIF.
You could Write a custom page inherits from 'ContentPage' and add toolbar item to it.
Update
I achieve it with DependencyService, If you want to know more details about how to achieve DependencyService, you could refer to this blog and my code.
https://www.xamboy.com/2018/03/08/adding-badge-to-toolbaritem-in-xamarin-forms/
There is code that used DependencyService.
Custom ToolbarPage
public class ToolbarPage : ContentPage
{
public ToolbarItem toolbarItem;
public static int item;
public ToolbarPage()
{
// public ToolbarItem(string name, string icon, Action activated, ToolbarItemOrder order = ToolbarItemOrder.Default, int priority = 0);
toolbarItem =new ToolbarItem();
toolbarItem.Icon = "ring2.png";
toolbarItem.Order = ToolbarItemOrder.Primary;
// toolbarItem.Text = item+"";
toolbarItem.Priority = 0;
toolbarItem.Clicked += ToolbarItem_Clicked;
ToolbarItems.Add(toolbarItem);
if (item >= 1)
{
DependencyService.Get<IToolbarItemBadgeService>().SetBadge(this, toolbarItem, $"{item}", Color.Red, Color.White);
}
}
private void ToolbarItem_Clicked(object sender, EventArgs e)
{
item = item + 1;
DependencyService.Get<IToolbarItemBadgeService>().SetBadge(this, toolbarItem, $"{item}", Color.Red, Color.White);
}
}
Main.cs
public partial class MainPage : ToolbarPage
{
public MainPage()
{
InitializeComponent();
bt1.Text = ToolbarPage.item.ToString();
bt1.Clicked += async (o, e) =>
{
await Navigation.PushAsync(new HelloToolbarInher());
};
}
protected override async void OnAppearing()
{
//You must make a delay,
await Task.Delay(100);
bt1.Text = ToolbarPage.item.ToString();
DependencyService.Get<IToolbarItemBadgeService>().SetBadge(this, toolbarItem, $"{ToolbarPage.item}", Color.Red, Color.White);
}
}
Do not forget to change MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<local:ToolbarPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:NaviagationViewDemo"
x:Class="NaviagationViewDemo.MainPage">
<StackLayout>
<!-- Place new controls here -->
<Button
x:Name="bt1"
Text="click"
></Button>
</StackLayout>
There is my new demo.
https://github.com/851265601/NewNaviagationViewDemo

Xamarin Forms - Hide navigation bar in MasterDetailPage

I need hide navigation bar in xamarin forms 3.0.
I try this, but dont work:
Hide Navigation Bar on MasterDetailPage
I want hide navigation bar for create a custom bar, also I need a way to open menu.
Thanks.
App.xaml.cs
public partial class App : Application
{
public App ()
{
InitializeComponent();
MainPage = new MainPage();
}
...
MainPage.xaml.cs
public partial class MainPage : MasterDetailPage
{
public List<MasterPageItem> menuList { get; set; }
public MainPage()
{
InitializeComponent();
menuList = new List<MasterPageItem>();
menuList.Add(new MasterPageItem() { Title = "Home", Icon = "home.png", TargetType = typeof(HomePage) });
menuList.Add(new MasterPageItem() { Title = "Settings", Icon = "setting.png", TargetType = typeof(SettingsPage) });
menuList.Add(new MasterPageItem() { Title = "Help", Icon = "help.png", TargetType = typeof(HelpPage) });
navigationDrawerList.ItemsSource = menuList;
var navPage = new NavigationPage((Page)Activator.CreateInstance(typeof(HomePage)));
//I try this:
NavigationPage.SetHasNavigationBar(navPage, false);
NavigationPage.SetHasBackButton(navPage, false);
Detail = navPage;
}
...
MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:App3"
x:Class="App3.MainPage">
<MasterDetailPage.Master>
<ContentPage Title="Menu">
<Grid BackgroundColor="Transparent">
<StackLayout Grid.Row="1" Spacing="15">
...
</StackLayout>
</Grid>
</ContentPage>
</MasterDetailPage.Master>
<MasterDetailPage.Detail>
<NavigationPage>
</NavigationPage>
</MasterDetailPage.Detail>
</MasterDetailPage>
Source repo:
https://github.com/uiahhh/stackoverflow/tree/master/HideNavBar
I want remove this navbar in red circle:
On the detail page you have to remove the navigation bar with NavigationPage.SetHasNavigationBar(this, false); in the constructor right after InitializeComponent()
public partial class MyPage : NavigationPage
{
public MyPage()
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
}
}
In addition to Pedro's answer, you can also hide the navigation bar in your .xaml file. For example:
<ContentPage NavigationPage.HasNavigationBar="False">
...
</ContentPage>
Note: This works in Xamarin 4.0 but I haven't tested it in 3.0.

Xamarin Forms ListView text not displayed

I'm new to Xamarin Forms, I'm following the official tutorial for learning Xamarin forms. While learning about navigation using Phoneword project of the following link
https://developer.xamarin.com/guides/xamarin-forms/getting-started/hello-xamarin-forms-multiscreen/quickstart/
The listview text is not appearing. Please help me!
CallHistoryPage.xaml: Here the listview is there.
<?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:App1;assembly=App1"
x:Class="App1.CallHistoryPage"
Title="Call History">
<ContentPage.Padding>
<OnPlatform x:TypeArguments="Thickness">
<On Platform="iOS" Value="20, 40, 20, 20"/>
<On Platform="Android" Value="20"/>
</OnPlatform>
</ContentPage.Padding>
<StackLayout>
<ListView ItemsSource="{x:Static local:App.PhoneNumbers}" />
</StackLayout>
</ContentPage>
MainPage.xaml.cs: SourceItem values are updated in this class.
namespace App1
{
public partial class MainPage : ContentPage
{
string translatedNumber;
public MainPage()
{
InitializeComponent();
}
void OnTranslate(object sender, EventArgs e)
{
translatedNumber = PhonewordTranslator.ToNumber(phoneNumberText.Text);
if (!string.IsNullOrWhiteSpace(translatedNumber))
{
callButton.IsEnabled = true;
callButton.Text = "Call " + translatedNumber;
}
else
{
callButton.IsEnabled = false;
callButton.Text = "Call";
}
}
async void OnCall(object sender, EventArgs e)
{
if (await this.DisplayAlert(
"Dial a Number",
"Would you like to call " + translatedNumber + "?",
"Yes",
"No"))
{
var dialer = DependencyService.Get<IDialer>();
if (dialer != null)
{
App.PhoneNumbers.Add(translatedNumber);
callHistoryButton.IsEnabled = true;
dialer.Dial(translatedNumber);
}
}
}
async void OnCallHistory(object sender, EventArgs e)
{
await Navigation.PushAsync(new CallHistoryPage());
}
}
}
App.xaml.cs: Sourceitem for listview is in this class
namespace App1
{
public partial class App : Application
{
public static IList<string> PhoneNumbers { get; set; }
public App()
{
InitializeComponent();
PhoneNumbers = new List<string>();
MainPage = new NavigationPage(new MainPage());
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
For more details please follow the link added above. Same tutorial is followed.
You forgot to 'tell' ListView what to display.
<ListView ItemsSource="{x:Static local:App.PhoneNumbers}" />
creates a ListView with empty cells, hence they are not displaying anything. You'll have to set the ListView.ItemTemplate in order to display anything
<ListView ItemsSource="{x:Static local:App.PhoneNumbers}">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding .}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The BindingContext within the DataTemplate will be the respective item from App.PhoneNumbers. Since the items are bare strings we bind to ., which refers to the bound element itself.
See here for ListViews in Xamarin.Forms.
You have not added any numbers in PhoneNumbers list. Add number first in PhoneNumbers list and then check.
public App()
{
InitializeComponent();
PhoneNumbers = new List<string>();
PhoneNumbers.Add("123456789");
PhoneNumbers.Add("178967897");
PhoneNumbers.Add("178945678");
MainPage = new NavigationPage(new MainPage());
}
I think you have forget to take input from user.So add this line in OnCall method
translatedNumber = PhonewordTranslator.ToNumber(phoneNumberText.Text);
Try this,
async void OnCall(object sender, EventArgs e)
{
translatedNumber = PhonewordTranslator.ToNumber(phoneNumberText.Text);
if (await this.DisplayAlert(
"Dial a Number",
"Would you like to call " + translatedNumber + "?",
"Yes",
"No"))
{
var dialer = DependencyService.Get<IDialer>();
if (dialer != null)
{
App.PhoneNumbers.Add(translatedNumber);
callHistoryButton.IsEnabled = true;
dialer.Dial(translatedNumber);
}
}
}

Resources