How to set Focus to entry in xamarin forms - xamarin

I want to add focus() to my entry field, When I add the entry.Focus() it's work fine in the entry's in top of the page.But when comes to the bottom it doesn't work smoothly.And also I tried with SoftInput method but it hides the entry in the bottom and also the design is changing when a page has only one or two entry.
Please help me

The #AbbyWang answer is correct, also you can use the ReturnCommand property.
<StackLayout
Orientation="Vertical">
<Entry
x:Name="firstLabel"
ReturnType="Next"
FontSize="Small"
TextColor="Black" />
<Entry
x:Name="secondLabel"
ReturnType="Done"
FontSize="Small"
TextColor="Black" />
</StackLayout>
And the code behind
public YourPage()
{
InitializeComponent();
this.firstLabel.ReturnCommand = new Command(() => this.secondLabel.Focus());
// or you can use this to call a command on your viewmodel
this.secondLabel.ReturnCommand = new Command(() => YourViewModel.SomeCommand.Execute(null));
}

If you just have two Entries on your page, you can simply add a Completed event to your top entry, and call the entry.Focus() for bottom entry in this event. So the code is like this:
MainPage.xaml:
<StackLayout>
<StackLayout Orientation="Horizontal" VerticalOptions="Start">
<!-- Place new controls here -->
<Entry Text="top" x:Name="TopEntry"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand"
Completed="Entry_Completed" />
</StackLayout>
<StackLayout Orientation="Horizontal" VerticalOptions="End">
<!-- Place new controls here -->
<Entry Text="Bottom" x:Name="BottomEntry"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" />
</StackLayout>
</StackLayout>
MainPage.xaml.cs
void Entry_Completed(object sender, EventArgs e)
{
BottomEntry.Focus();
}
If you have many more than 2 entries and you want to focus on next entry when press the "done" on keyboard, you can also refer to this.

Related

Hints for programming a Xamarin.Forms application

Sorry for my perhaps silly question. As I am new to Xamarin Forms, I need some basic hints:
I need a window ("secondary window") sliding from left into my main window. In this window, a list of items (with images and text) should be displayed and this window should cover only 1/4 to 1/2 of my main window. Dragging an item from this secondary window to the main window should start some action with this item on main window.
What type of view is best for this purpose and what are the keywords to search for? This looks like a flyout menu but how can I create such view from my main menu or clicking on a button?
I am using C# and Visual Studio 2022
Maybe like this , one page (ContentPage) with a Grid in a Grid.
The Grid MainContentGrid is sliding and the MenuContainer Grid is showing.
Then use Drag and Drop to put the Like Image in MenuContainer on the Drophere Image in MainContentGrid, then an event.
The MainContentGrid is using TranslateTo to slide away and back.
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/gestures/drag-and-drop
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/animation/simple
The MainPage
<Grid>
<!-- Menu Grid -->
<Grid x:Name="MenuContainer" BackgroundColor="Gray">
<StackLayout
Margin="24,100,0,0"
HorizontalOptions="Start"
Spacing="30">
<Label
FontSize="28"
HorizontalOptions="Center"
Text="MENU Options" />
<Image
HeightRequest="50"
HorizontalOptions="Center"
Source="imglike.png"
VerticalOptions="Center"
WidthRequest="50">
<Image.Clip>
<EllipseGeometry
Center="25,25"
RadiusX="25"
RadiusY="25" />
</Image.Clip>
<Image.GestureRecognizers>
<DragGestureRecognizer />
</Image.GestureRecognizers>
</Image>
</StackLayout>
</Grid>
<!-- Main Content -->
<Grid
x:Name="MainContentGrid"
Padding="24,5,24,0"
BackgroundColor="Red"
ColumnDefinitions="*,Auto"
RowDefinitions="Auto,*">
<!-- Header Text -->
<StackLayout
Grid.Row="0"
Grid.Column="1"
Spacing="4"
VerticalOptions="Center">
<Label Text="Slide Menu" />
</StackLayout>
<!-- Hamburger Pic -->
<Frame
Grid.Row="0"
Grid.Column="0"
BackgroundColor="Red"
BorderColor="Gray"
CornerRadius="28"
HeightRequest="56"
HorizontalOptions="Start"
VerticalOptions="Center"
WidthRequest="56">
<Frame.GestureRecognizers>
<TapGestureRecognizer Tapped="ProfilePic_Clicked" />
</Frame.GestureRecognizers>
<Image
HeightRequest="50"
HorizontalOptions="Center"
Source="icnhamburger.png"
VerticalOptions="Center"
WidthRequest="50">
<Image.Clip>
<EllipseGeometry
Center="25,25"
RadiusX="25"
RadiusY="25" />
</Image.Clip>
</Image>
</Frame>
<Frame
Grid.Row="1"
Grid.Column="0"
BackgroundColor="Red"
BorderColor="Gray"
CornerRadius="28"
HeightRequest="56"
HorizontalOptions="Start"
VerticalOptions="Center"
WidthRequest="56">
<Image
Aspect="AspectFill"
HeightRequest="50"
HorizontalOptions="Center"
Source="drop.png"
VerticalOptions="Center"
WidthRequest="50">
<Image.GestureRecognizers>
<DropGestureRecognizer Drop="DropGestureRecognizer_Drop" />
</Image.GestureRecognizers>
</Image>
</Frame>
</Grid>
</Grid>
MainPage.cs
public partial class MainPage : ContentPage
{
private const uint AnimationDuration = 500u;
public MainPage()
{
InitializeComponent();
}
private async Task CloseMenu()
{
//Close the menu and bring back back the main content
_ = MainContentGrid.FadeTo(1, AnimationDuration);
_ = MainContentGrid.ScaleTo(1, AnimationDuration);
await MainContentGrid.TranslateTo(0, 0, AnimationDuration, Easing.CubicIn);
}
async void ProfilePic_Clicked(System.Object sender, System.EventArgs e)
{
// Reveal our menu and move the main content out of the view
_ = MainContentGrid.TranslateTo(this.Width * 0.5, this.Height * 0, AnimationDuration, Easing.CubicIn);
await MainContentGrid.ScaleTo(0.8, AnimationDuration);
_ = MainContentGrid.FadeTo(0.8, AnimationDuration);
}
private async void DropGestureRecognizer_Drop(object sender, DropEventArgs e)
{
await CloseMenu();
await DisplayAlert("Job", "I have a job for you to do !", "OK");
}
}
This is how it looks

How to place focus on my custom input , I am using mvvm , prism

One query I have an entry in a contentview to be able to call it from another page.
the question is how to locate the focus when I click on a button
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
x:Class="MovilERP.Controls.SacTextBox"
x:Name="this">
<Grid RowDefinitions="Auto,Auto">
<!--#region Entry Normal-->
<Grid RowDefinitions="Auto,1"
ColumnDefinitions="*,Auto" RowSpacing="0">
<Entry x:Name="txtBox"
Margin="{OnPlatform Android=0 , iOS=5}"
Text="{Binding Text, Source={x:Reference this}}"
PlaceholderColor="{DynamicResource PlaceHolderColorEntry}"
Style="{StaticResource EstiloEntry}"
IsPassword="{Binding ShowIcoPassword, Source={x:Reference this}}"
IsSpellCheckEnabled="{Binding IsCorrector, Source={x:Reference this}}"
IsTextPredictionEnabled="True">
</grid>
</grid>
</Conteview>
this is how i invoke it from another page
<sofadControls:SacTextBox
x:Name="Descripcion"
Grid.Column="1"
Placeholder="Descripción"
SacAlineacion="Start"
SacValidacion="AlfaNumerico"
Text="{Binding Source={RelativeSource AncestorType={x:Type dialogos:FrmArticulosGeneralViewModel}}, Path=DetalleActual.Descripcion}"/>
In this way I try to invoke the focus but it does not work
Descripcion.Focus();
you need to create a public method in your control
public void Focus()
{
txtBox.Focus();
}
then you can call that public Focus method from the oage that contains your control

Xamarin - Entry Focused and TapGestureRecognizer not working

<StackLayout Orientation="Horizontal" FlowDirection="RightToLeft" HorizontalOptions="EndAndExpand" Spacing="0">
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Tapped="GoToBasket"></TapGestureRecognizer>
</StackLayout.GestureRecognizers>
<Frame x:Name="frmBasket" CornerRadius="24" Padding="8" BackgroundColor="#FFFFFF">
<StackLayout Orientation="Horizontal">
<Entry x:Name="lblTotalBasket" TextChanged="lblTotalBasket_TextChanged" HorizontalOptions="FillAndExpand" IsReadOnly="True" Text="{Binding TotalPrice, StringFormat='₺{0:0.00}'}" Margin="0, 0, 5, 0" HorizontalTextAlignment="Center" FontSize="13" VerticalTextAlignment="Center" FontAttributes="Bold" BackgroundColor="#FFFFFF" TextColor="{StaticResource Primary}"></Entry>
<Label x:Name="lblBasketIcon" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" BackgroundColor="Transparent" Text="" FontSize="15" TextColor="{StaticResource Primary}" Margin="8, 0, 0, 0" FontFamily="{StaticResource FontAwesomeSolid}"></Label>
</StackLayout>
</Frame>
</StackLayout>
StackLayout TapGestureRecognizer working except Entry element. I tried add TapGestureRecognizer and Focused attribute for Entry element but also not worked.
How StackLayout TapGestureRecognizer does work on Entry element tap ?
If you set the IsReadOnly=false to entry, the TapGestureRecognizer won't work because it will get fouced when tap it and user can type something. In this cause, you can call your method in the foucsed event:
<Entry x:Name="lblTotalBasket" Focused="lblTotalBasket_Focused"/>
And in code behind:
private void lblTotalBasket_Focused(object sender, FocusEventArgs e)
{
Console.WriteLine("lblTotalBasket_Focused-entry");
}
If you set the IsReadOnly=ture to entry, the TapGestureRecognizer will execute and you can also add TapGestureRecognizer to entry directly:
<Entry x:Name="lblTotalBasket" Focused="lblTotalBasket_Focused" HorizontalOptions="FillAndExpand" IsReadOnly="True" Text="{Binding TotalPrice, StringFormat='₺{0:0.00}'}" Margin="0, 0, 5, 0" HorizontalTextAlignment="Center" FontSize="13" VerticalTextAlignment="Center" FontAttributes="Bold" BackgroundColor="#FFFFFF">
<Entry.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"></TapGestureRecognizer>
</Entry.GestureRecognizers>
</Entry>
And in code behind:
private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
Console.WriteLine("TapGestureRecognizer_Tapped-entry");
}
Update:
In Android, you also need to set isEnable = false to make TapGestureRecognizer work:
<Entry x:Name="lblTotalBasket" IsEnabled="False"/>
Try setting TapGesture for parent control and for your entry set InputTransparent="True" so that when you tap on entry it will actually recognized as tap on parent control.

Focus on entry in listview on android

So i need to allow the user to get access to each entry field within the listview to enter a value, my code runs fine on iOS but once to try it on android i cant get access to the entry box, once the entry field is tapped it will show the cursor but it will not focus on the entry field and you cannot type anything as the keyboard doesnt appear. Does anyone have any idea how to fix this issue ?
<ListView x:Name="btnlist" Margin="0,0,0,20" Grid.Row="8" Grid.Column="1" Grid.ColumnSpan="2" AutomationId="ListMed"
CachingStrategy="RecycleElement" RowHeight="65" IsPullToRefreshEnabled="False" IsVisible="false" SeparatorColor="transparent"
>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell Appearing="Handle_Appearing1">
<local:XFDoneEntry x:Name="txtFrequency" Text="{Binding Count}" Day="{Binding Placeholder}" wdaynum="{Binding Wdaynum}" Placeholder="{Binding Placeholder}" Unfocused="Leave_box" VerticalOptions="Center" Keyboard="Numeric" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3"/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
//This is the code i use to find the entry boxes within the listview.
void Handle_Appearing1(object sender, System.EventArgs e)
{
var ViewcellAll1 = (ViewCell)sender;
ddoneentry = ViewcellAll1.View.FindByName<XFDoneEntry>("txtFrequency");
}
//this is the app with the listviews, depending on which days the user chooses the appropriate entry fields are populated within the second listview with entries.

Is there a way to simulate the clicking of a button?

I'm using this code to create something looking like a button:
<Grid Grid.Column="0" ColumnSpacing="0" Margin="0,0,10,0">
<Frame Grid.Column="0" CornerRadius="5" OutlineColor="Black">
<Label x:Name="faveIconLabel" Style="{StaticResource mediumIcon}" Margin="0,2,0,0" HorizontalOptions="Fill" FontFamily="FontAwesome" VerticalOptions="Center" VerticalTextAlignment="Center" />
</Frame>
<Frame Grid.Column="1" CornerRadius="5" OutlineColor="Black">
<Label x:Name="hiddenIconLabel" Style="{StaticResource mediumIcon}" Margin="0,2,0,0" HorizontalOptions="Fill" FontFamily="FontAwesome" VerticalOptions="Center" VerticalTextAlignment="Center" />
</Frame>
</Grid>
Is there a way that I can simulate the click event to make it look like something actually got pressed when they click on the label?
If you don't want to use a custom renderer, a simple way would be to change the background color in the handleClick, and then revert it back to its original color after a few milliseconds. For example,
private void handleClick(object sender, EventArgs e) {
var view = (View)sender;
view.BackgroundColor = Color.FromHex("#DD000000");
Device.StartTimer(
TimeSpan.FromMilliseconds(100),
() =>
{
// Revert it back to the original color, whatever it may be.
Device.BeginInvokeOnMainThread(() =>
{
view.BackgroundColor = Color.Transparent;
});
return false; // return false to prevent the timer from calling again
});
}
You can add a TapGestureRecognizer to virtually any VisualElement, including Label, Image, etc.
faveIconLabel.GestureRecognizers.Add(new TapGestureRecognizer((view) => OnLabelClicked()));

Resources