How to Change the Radio Button Position in Xamarin? - xamarin

I have implemented Radio button using custom rendering in Xamarin. The radio button is aligned left and text is aligned right by default. How can we change the position of radio button to the right?
Xaml Code is below
<StackLayout HorizontalOptions="Start" VerticalOptions="CenterAndExpand">
<control:BindableRadioGroup x:Name="SortPicker"
TextColor="Gray"
CheckedChanged="OnCheckedChanged"
Padding="50,0,0,10"
WidthRequest="1100"
Spacing="20">
</control:BindableRadioGroup>
</StackLayout>
Render Code:
protected override void OnElementChanged(ElementChangedEventArgs<CustomRadioButton> e)
{
base.OnElementChanged(e);
if (Control == null)
{
var radButton = new RadioButton(Context);
colorStateList = radButton.TextColors;
radButton.CheckedChange += this.RadButtonCheckedChange;
SetNativeControl(radButton);
}
Control?.SetPadding(30, Control.PaddingTop, 0, Control.PaddingBottom);
Control.Text = e.NewElement.Text;
Control.Checked = e.NewElement.Checked;
UpdateTextColor();
if (e.NewElement.FontSize > 0)
{
Control.TextSize = (float)e.NewElement.FontSize;
}
if (!string.IsNullOrEmpty(e.NewElement.FontName))
{
Control.Typeface = TrySetFont(e.NewElement.FontName);
}
}

Try enabling supportsRtl property to true in your application manifest:
<application android:label="app label" android:supportsRtl="true"/>
and setting the Control's LayoutDirectionProperty like so:
Control.LayoutDirection = LayoutDirection.Rtl;

Related

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>

Best approach for show/hide password toggle functionality in Xamarin traditional approach

We are working on show/ hide password toggle functionality in Xamarin traditional approach. What is the best place to implement it? Is it in Xamarin.iOS &. Droid or in Xamarin.Core?
If it is in Xamarin.Core, can you let us know the process. Is it by value convertors?
Thanks in advance.
Recently, Microsoft MVP Charlin, wrote an article showing how to do this using Event Triggers in the Xamarin Forms code:
She was able to do it simply using a new ShowPasswordTriggerAction of type TriggerAction that implemented INotifyPropertyChanged.
Therein, she created a HidePassword bool property that Invoke a PropertyChanged event which changes the Source of the Icon image:
protected override void Invoke(ImageButton sender)
{
sender.Source = HidePassword ? ShowIcon : HideIcon;
HidePassword = !HidePassword;
}
Then place the Entry and ImageButton inside a layout (like a Frame or horizontally oriented LinearLayout) as shown:
<Entry Placeholder="Password"
IsPassword="{Binding Source={x:Reference ShowPasswordActualTrigger}, Path=HidePassword}"/>
<ImageButton VerticalOptions="Center"
HeightRequest="20"
HorizontalOptions="End"
Source="ic_eye_hide">
<ImageButton.Triggers>
<EventTrigger Event="Clicked">
<local:ShowPasswordTriggerAction ShowIcon="ic_eye"
HideIcon="ic_eye_hide"
x:Name="ShowPasswordActualTrigger"/>
</EventTrigger>
</ImageButton.Triggers>
</ImageButton>
We always use custom controls to show/hide password while entering the password using effects.
Android:
Create the control manually in ‘OnDrawableTouchListener’ method where, we are adding the ShowPass and HidePass icons to the entry control, changing them on the basis of user touch action and attaching it on effect invocation which will be fired when the effect is added to the control.
public class OnDrawableTouchListener : Java.Lang.Object, Android.Views.View.IOnTouchListener
{
public bool OnTouch(Android.Views.View v, MotionEvent e)
{
if (v is EditText && e.Action == MotionEventActions.Up)
{
EditText editText = (EditText)v;
if (e.RawX >= (editText.Right - editText.GetCompoundDrawables()[2].Bounds.Width()))
{
if (editText.TransformationMethod == null)
{
editText.TransformationMethod = PasswordTransformationMethod.Instance;
editText.SetCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, Resource.Drawable.ShowPass, 0);
}
else
{
editText.TransformationMethod = null;
editText.SetCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, Resource.Drawable.HidePass, 0);
}
return true;
}
}
return false;
}
}
Result:
IOS:
Create the control manually in 'ConfigureControl' method where we are adding the ShowPass and HidePassicons to the entry control, changing them on the basis of user touch action; and attaching it on effect invocation which will be fired when the effect will be added to the control.
private void ConfigureControl()
{
if (Control != null)
{
UITextField vUpdatedEntry = (UITextField)Control;
var buttonRect = UIButton.FromType(UIButtonType.Custom);
buttonRect.SetImage(new UIImage("ShowPass"), UIControlState.Normal);
buttonRect.TouchUpInside += (object sender, EventArgs e1) =>
{
if (vUpdatedEntry.SecureTextEntry)
{
vUpdatedEntry.SecureTextEntry = false;
buttonRect.SetImage(new UIImage("HidePass"), UIControlState.Normal);
}
else
{
vUpdatedEntry.SecureTextEntry = true;
buttonRect.SetImage(new UIImage("ShowPass"), UIControlState.Normal);
}
};
vUpdatedEntry.ShouldChangeCharacters += (textField, range, replacementString) =>
{
string text = vUpdatedEntry.Text;
var result = text.Substring(0, (int)range.Location) + replacementString + text.Substring((int)range.Location + (int)range.Length);
vUpdatedEntry.Text = result;
return false;
};
buttonRect.Frame = new CoreGraphics.CGRect(10.0f, 0.0f, 15.0f, 15.0f);
buttonRect.ContentMode = UIViewContentMode.Right;
UIView paddingViewRight = new UIView(new System.Drawing.RectangleF(5.0f, -5.0f, 30.0f, 18.0f));
paddingViewRight.Add(buttonRect);
paddingViewRight.ContentMode = UIViewContentMode.BottomRight;
vUpdatedEntry.LeftView = paddingViewRight;
vUpdatedEntry.LeftViewMode = UITextFieldViewMode.Always;
Control.Layer.CornerRadius = 4;
Control.Layer.BorderColor = new CoreGraphics.CGColor(255, 255, 255);
Control.Layer.MasksToBounds = true;
vUpdatedEntry.TextAlignment = UITextAlignment.Left;
}
}
Result:
For more details, please refer to the article below.
https://www.c-sharpcorner.com/article/xamarin-forms-tip-implement-show-hide-password-using-effects/
You could download the source file from GitHub for reference.
https://github.com/techierathore/ShowHidePassEx.git
You can use the PhantomLib library to do this. It has a control which allows you to have a show/hide icon for the password with examples. Just install the nuget. https://github.com/OSTUSA/PhantomLib
Your UI codes like this having a entry and image button
source to named accroding to your ui
<Frame CornerRadius="30" Background="white" Padding="0" HeightRequest="43" Margin="0,17,0,0">
<StackLayout Orientation="Horizontal">
<Entry x:Name="eLoginPassword"
Margin="15,-10,0,-15"
HorizontalOptions="FillAndExpand"
IsPassword="True"
Placeholder="Password"/>
<ImageButton
x:Name="ibToggleLoginPass"
Clicked="IbToggleLoginPass"
Source="eyeclosed"
Margin="0,0,13,0"
BackgroundColor="White"
HorizontalOptions="End"
/>
</StackLayout>
</Frame>
in C# code
// IbToggleLoginPass your defined method in xaml
//"eye" is drawable name for open eye and "eyeclosed" is drawable name for closed eye
private void IbToggleLoginPass(object sender, EventArgs e)
{
bool isPass = eLoginPassword.IsPassword;
ibToggleLoginPa`enter code here`ss.Source = isPass ? "eye" : "eyeclosed";
eLoginPassword.IsPassword = !isPass;
}
Trigger and a command
The trigger changes the icon, and the command changes the entry.
View xaml
<Grid>
<Entry Placeholder="Password" Text="{Binding Password, Mode=TwoWay}" IsPassword="{Binding IsPassword}" />
<ImageButton BackgroundColor="Transparent" WidthRequest="24" VerticalOptions="Center" TranslationY="-5" TranslationX="-10" HorizontalOptions="End"
Command="{Binding ToggleIsPassword}"
Source="eye" >
<ImageButton.Triggers>
<DataTrigger TargetType="ImageButton" Binding="{Binding IsPassword}" Value="True" >
<Setter Property="Source" Value="eye-slash" />
</DataTrigger>
</ImageButton.Triggers>
</ImageButton>
</Grid>
And in my ViewModel
private bool _IsPassword = true;
public bool IsPassword
{
get
{
return _IsPassword;
}
set
{
_IsPassword = value;
RaisePropertyChanged(() => IsPassword);
}
}
public ICommand ToggleIsPassword => new Command(() => IsPassword = !IsPassword);

How to prevent Editor to go behind the keyboard in Xamarin.Forms?

I have a Chat app. Currently, there is an Entry control for add chat text. Now I want to provide multiline Entry, same like Whatsapp.
If user type more than one line, it should automatic wrap the text to next line.
If user click on Nextline button in mobile keyboard, it should go to next line.
Height of Entry should be automatically increase upto 3 line and it should also decrease if user remove text.
To do that I have tried to replace Entry with Editor and implement following functionality.
1- Put an Editor in place of Entry.
2- Implement a functionality that keep keyboard open until user click on Message list screen or back button.
Now I am trying to implement auto height functioanlity but when user try to type, Editor goes behind the keyboard. Can anybody please suggest me how to keep Editor open and auto size?
Current code:
XAML:
<Grid x:Name="MessageControls" RowSpacing="1" ColumnSpacing="2" Padding="5"
Grid.Row="1" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="auto" />
</Grid.ColumnDefinitions>
<local:ChatEditorWithPlaceholder x:Name="txtMessage" Grid.Column="0" TextChanged="EnableSend" Text="{Binding OutGoingText}"/>
<Frame x:Name="SendButton" Grid.Column="1" Margin= "0" Padding="0" HasShadow="false" HeightRequest="25"
BackgroundColor="Transparent" HorizontalOptions="FillAndExpand">
<Frame.GestureRecognizers>
<TapGestureRecognizer Tapped="SendMessage_Click" NumberOfTapsRequired="1" />
</Frame.GestureRecognizers>
<Label Text="Send" x:Name="sendButton" TextColor="#1f88b7" HeightRequest="20"
HorizontalOptions="Center" VerticalOptions="Center"/>
</Frame>
</Grid>
Editor
public class ChatEditorWithPlaceholder : Editor
{
public ChatEditorWithPlaceholder()
{
this.TextChanged += (sender, e) => { this.InvalidateMeasure(); };
}
}
Editor Renderer:
public class ChatEditorRenderer : EditorRenderer
{
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
}
}
protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
{
base.OnElementChanged(e);
if(Control != null) {
Control.ScrollEnabled = false;
}
var element = this.Element as ChatEditorWithPlaceholder;
Control.InputAccessoryView = null;
Control.ShouldEndEditing += DisableHidingKeyboard;
MessagingCenter.Subscribe<ConversationPage>(this, "FocusKeyboardStatus", (sender) =>
{
if (Control != null)
{
Control.ShouldEndEditing += EnableHidingKeyboard;
}
MessagingCenter.Unsubscribe<ConversationPage>(this, "FocusKeyboardStatus");
});
}
private bool DisableHidingKeyboard(UITextView textView)
{
return false;
}
private bool EnableHidingKeyboard(UITextView textView)
{
return true;
}
Screenshots:
Try this renderer for ios.
using System;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly:ExportRenderer( typeof(CustomEditor), typeof(CustomEditorRenderer))]
namespace YourNameSpace.iOS
{
public class CustomEditorRenderer: EditorRenderer
{
public ChatEntryRenderer()
{
UIKeyboard.Notifications.ObserveWillShow ((sender, args) => {
if (Element != null)
{
Element.Margin = new Thickness(0,0,0, args.FrameEnd.Height); //push the entry up to keyboard height when keyboard is activated
}
});
UIKeyboard.Notifications.ObserveWillHide ((sender, args) => {
if (Element != null)
{
Element.Margin = new Thickness(0); //set the margins to zero when keyboard is dismissed
}
});
}
}
}
for android add this in MainActivity
App.Current.On<Xamarin.Forms.PlatformConfiguration.Android>().
UseWindowSoftInputModeAdjust(WindowSoftInputModeAdjust.Resize);
For Ios there is one plugin. You can use that. The link is Here.
For Andorid you have to just set below code in MainActivity after LoadApplication(new App()) method.
App.Current.On<Xamarin.Forms.PlatformConfiguration.Android().
UseWindowSoftInputModeAdjust(WindowSoftInputModeAdjust.Resize);
Updated answer for iOS :
For IOS you can use the following custom renderer to solve the keyboard overlapping issue. And please removed the keyboardoverlap nuget package from the project.
using System;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using HBIClientFacingApp;
using HBIClientFacingApp.iOS;
[assembly:ExportRenderer( typeof(CustomEditor), typeof(CustomEditorRenderer))]
namespace YourNameSpace.iOS
{
public class CustomEditorRenderer: EditorRenderer
{
public ChatEntryRenderer()
{
UIKeyboard.Notifications.ObserveWillShow ((sender, args) => {
if (Element != null)
{
Element.Margin = new Thickness(0,0,0, args.FrameEnd.Height); //push the entry up to keyboard height when keyboard is activated
}
});
UIKeyboard.Notifications.ObserveWillHide ((sender, args) => {
if (Element != null)
{
Element.Margin = new Thickness(0); //set the margins to zero when keyboard is dismissed
}
});
}
}
}
You can try to change this line:
<local:ChatEditorWithPlaceholder x:Name="txtMessage" Grid.Column="0" TextChanged="EnableSend" Text="{Binding OutGoingText}"/>
For this one:
<Editor x:Name="txtMessage" Grid.Column="0" AutoSize="TextChanges" TextChanged="EnableSend" Text="{Binding OutGoingText}"/>

Xamarin.Forms ScrollView - animate its growth as it expands

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.
Relevant existing code below (we're using Forms with MvvmCross - hence an MVVM pattern):
ViewModel
private async Task NextClick()
{
var claimFlowQuestion = await GetClaimFlowQuestion(_currentIndexQuestion);
Questions.Add(ClaimFlowExtendFromClaimFlow(claimFlowQuestion));
// Trigger PropertyChanged so the Repeater updates
await RaisePropertyChanged(nameof(Questions));
// Trigger the QuestionAdded event so the ScrollView can scroll to the bottom (initiated in the xaml.cs code behind)
QuestionAdded?.Invoke(this, new EventArgs());
}
XAML
<ScrollView Grid.Row="1" x:Name="QuestionScrollView">
<StackLayout VerticalOptions="End"
Padding ="10,0,10,0"
IsVisible="{Binding Busy, Converter={StaticResource InvertedBooleanConvertor}}}">
<controls:RepeaterView
x:Name="QuestionRepeater"
Margin ="10"
AutomationId="IdQuestions"
Direction ="Column"
ItemsSource ="{Binding Questions}"
ClearChild ="false">
<controls:RepeaterView.ItemTemplate>
<DataTemplate>
<ViewCell>
<controlsClaimFlowControls:QuestionBlock
Margin ="0,20,0,20"
QuestionNumber ="{Binding Index}"
QuestionText ="{Binding QuestionText}"
QuestionDescription="{Binding QuestionDescription}"
ItemsSource ="{Binding Source}"
DisplayMemberPath ="{Binding DisplayPaths}"
QuestionType ="{Binding QuestionType}"
SelectedItem ="{Binding Value}"
IsEnabledBlock ="{Binding IsEnabled}" />
</ViewCell>
</DataTemplate>
</controls:RepeaterView.ItemTemplate>
</controls:RepeaterView>
</StackLayout>
</ScrollView>
XAML.cs
protected override void OnAppearing()
{
if (BindingContext != null)
{
MedicalClaimConditionPageModel model = (MedicalClaimConditionPageModel)this.BindingContext.DataContext;
model.QuestionAdded += Model_QuestionAdded;
}
base.OnAppearing();
}
protected override void OnDisappearing()
{
MedicalClaimConditionPageModel model = (MedicalClaimConditionPageModel)this.BindingContext.DataContext;
model.QuestionAdded -= Model_QuestionAdded;
base.OnDisappearing();
}
void Model_QuestionAdded(object sender, EventArgs e)
{
Device.BeginInvokeOnMainThread(async () =>
{
if (Device.RuntimePlatform == Device.iOS)
{
// We need a Task.Delay to allow the contained controls to repaint and have their new sizes
// Ultimately we should come up with a better resolution - the delay value can vary depending on device and OS version.
await Task.Delay(50);
}
await QuestionScrollView.ScrollToAsync(QuestionRepeater, ScrollToPosition.End, true);
});
}
A reasonable answer has been posted by user yelinzh on the Xamarin forums:
How about trying to use Custom Renderer such as the fading effect.
[assembly: ExportRenderer(typeof(ScrollView_), typeof(ScrollViewR))]
namespace App3.Droid
{
public class ScrollViewR : ScrollViewRenderer
{
public ScrollViewR(Context context) : base(context)
{
}
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
this.SetFadingEdgeLength(300);
this.VerticalFadingEdgeEnabled = true;
}
}
}
This would probably work. In fact we've got for a different approach
(after feedback from the customer), where we're keeping the current question at the top of the screen and scrolling off upwards, so the content is no longer expanding.

Is there any way to make a label fill the space from left to right?

Here is the code I have:
<StackLayout>
<Label x:Name="emptyLabel1" FontSize="18" XAlign="Start" TextColor="Gray" />
<Label x:Name="emptyLabel2" FontSize="18" XAlign="Center" TextColor="Gray" />
<Label x:Name="emptyLabel3" FontSize="18" XAlign="Center" TextColor="Gray" />
</StackLayout>
The first multi-line label starts on the left but has spaces on some of the rows on the right. The 2nd and 3rd multi-line labels are centered and have spaces on both left and right.
Is there any way that I can have all rows of the labels completely fill the rows completely fill from left to right o that the first character of each row always lines up on the left and the last character of the last word of each row always lines up on the right? Note that this would require some words in each line to have different gaps between them.
It is a bit tricky to implement label with justify alignment support, but it is possible through platform renderer(s).
First step would be to declare a custom control in forms project.
public class JustifiedLabel : Label { }
Next step is to define and register the platform renderer in iOS. This one is simple, as we simply combine formatted-string with paragraph-style to get what we want.
[assembly: ExportRenderer(typeof(JustifiedLabel), typeof(JustifiedLabelRenderer))]
namespace SomeAppNamespace.iOS
{
public class JustifiedLabelRenderer : LabelRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
//if we have a new forms element, we want to update text with font style (as specified in forms-pcl) on native control
if (e.NewElement != null)
UpdateTextOnControl();
}
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
//if there is change in text or font-style, trigger update to redraw control
if(e.PropertyName == nameof(Label.Text)
|| e.PropertyName == nameof(Label.FontFamily)
|| e.PropertyName == nameof(Label.FontSize)
|| e.PropertyName == nameof(Label.TextColor)
|| e.PropertyName == nameof(Label.FontAttributes))
{
UpdateTextOnControl();
}
}
void UpdateTextOnControl()
{
if (Control == null)
return;
//define paragraph-style
var style = new NSMutableParagraphStyle()
{
Alignment = UITextAlignment.Justified,
FirstLineHeadIndent = 0.001f,
};
//define attributes that use both paragraph-style, and font-style
var uiAttr = new UIStringAttributes()
{
ParagraphStyle = style,
BaselineOffset = 0,
Font = Control.Font
};
//define frame to ensure justify alignment is applied
Control.Frame = new RectangleF(0, 0, (float)Element.Width, (float)Element.Height);
//set new text with ui-style-attributes to native control (UILabel)
var stringToJustify = Control.Text ?? string.Empty;
var attributedString = new Foundation.NSAttributedString(stringToJustify, uiAttr.Dictionary);
Control.AttributedText = attributedString;
Control.Lines = 0;
}
}
}
In android platform, it is a bit trickier - as android doesn't support justify alignment for TextView - so we will need to use a WebView instead to get it to render the text.
(Note: You can also alternatively use an android library and use it instead of WebView)
[assembly: ExportRenderer(typeof(JustifiedLabel), typeof(JustifiedLabelRenderer))]
namespace SomeAppNamespace.Droid
{
//We don't extend from LabelRenderer on purpose as we want to set
// our own native control (which is not TextView)
public class JustifiedLabelRenderer : ViewRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<View> e)
{
base.OnElementChanged(e);
//if we have a new forms element, we want to update text with font style (as specified in forms-pcl) on native control
if (e.NewElement != null)
{
if (Control == null)
{
//register webview as native control
var webView = new Android.Webkit.WebView(Context);
webView.VerticalScrollBarEnabled = false;
webView.HorizontalScrollBarEnabled = false;
webView.LoadData("<html><body> </body></html>", "text/html; charset=utf-8", "utf-8");
SetNativeControl(webView);
}
//if we have a new forms element, we want to update text with font style (as specified in forms-pcl) on native control
UpdateTextOnControl();
}
}
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
//if there is change in text or font-style, trigger update to redraw control
if (e.PropertyName == nameof(Label.Text)
|| e.PropertyName == nameof(Label.FontFamily)
|| e.PropertyName == nameof(Label.FontSize)
|| e.PropertyName == nameof(Label.TextColor)
|| e.PropertyName == nameof(Label.FontAttributes))
{
UpdateTextOnControl();
}
}
void UpdateTextOnControl()
{
var webView = Control as Android.Webkit.WebView;
var formsLabel = Element as Label;
// create css style from font-style as specified
var cssStyle = $"margin: 0px; padding: 0px; text-align: justify; color: {ToHexColor(formsLabel.TextColor)}; background-color: {ToHexColor(formsLabel.BackgroundColor)}; font-family: {formsLabel.FontFamily}; font-size: {formsLabel.FontSize}; font-weight: {formsLabel.FontAttributes}";
// apply that to text
var strData =
$"<html><body style=\"{cssStyle}\">{formsLabel?.Text}</body></html>";
// and, refresh webview
webView.LoadData(strData, "text/html; charset=utf-8", "utf-8");
webView.Reload();
}
// helper method to convert forms-color to css-color
string ToHexColor(Color color)
{
var red = (int)(color.R * 255);
var green = (int)(color.G * 255);
var blue = (int)(color.B * 255);
var alpha = (int)(color.A * 255);
var hex = $"#{red:X2}{green:X2}{blue:X2}";
return hex;
}
}
}
Sample usage
<StackLayout Margin="20">
<Entry x:Name="InputEntry" />
<Label Margin="0,10,0,0" BackgroundColor="Navy" TextColor="White" Text="Normal Text Label" FontSize="15" HorizontalOptions="CenterAndExpand" />
<Label
FontSize="20"
FontAttributes="Bold"
Text="{Binding Text, Source={x:Reference InputEntry}}" />
<Label Margin="0,10,0,0" BackgroundColor="Navy" TextColor="White" Text="Justified Text Label" FontSize="15" HorizontalOptions="CenterAndExpand" />
<local:JustifiedLabel
FontSize="20"
FontAttributes="Bold"
Text="{Binding Text, Source={x:Reference InputEntry}}"
TextColor="Green"
BackgroundColor="Yellow"
VerticalOptions="FillAndExpand"
HorizontalOptions="FillAndExpand" />
</StackLayout>
I think you can try with
HorizontalOptions=LayoutOptions.FillAndExpand
HorizontalOptions
I never saw any simple solution for this, only workarounds like mentioned here.
You need to use a component or create your own solution for each platform.
I'm surprised no one brought this up yet...
A very simple way to achieve this same effect, is to enclose the label in its own StackLayout, like the following:
<StackLayout Orientation="Vertical" >
<Label Text="My Label" />
</StackLayout>
<Frame
Padding="8">
<Label
Text="This is centered"
HorizontalOptions="CenterAndExpand" />
</Frame>

Resources