Xamarin: Adding borders to the selected tab item - xamarin

In Xamarin.Forms on Android, I'm working on a section that uses a tabbed page. I'm attempting to place a set of borders around the selected item like such:
and
Is there any way that such a goal can be achieved using custom renderers?

According to your description, if you want to change selected item color in TabbedPage, you can use the following code:
<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage
x:Class="TabbedPageDemo.TabbedPage2"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
xmlns:local="clr-namespace:TabbedPageDemo"
android:TabbedPage.BarItemColor="Gray"
android:TabbedPage.BarSelectedItemColor="#3C9BDF"
android:TabbedPage.ToolbarPlacement="Bottom"
BarTextColor="Gray">
<!-- Pages can be added as references or inline -->
<ContentPage Title="Tab 1" />
<ContentPage Title="Tab 2" />
<ContentPage Title="Tab 3" />
</TabbedPage>
If you want to change selected item text size, you can use custom render to do this:
[assembly: ExportRenderer(typeof(ExtendedTabbedPage), typeof(ExtendedTabbedPageRenderer))]
namespace CustomTabbedPage.Droid
{
public class ExtendedTabbedPageRenderer : TabbedPageRenderer
{
Xamarin.Forms.TabbedPage tabbedPage;
BottomNavigationView bottomNavigationView;
Android.Views.IMenuItem lastItemSelected;
private bool firstTime = true;
int lastItemId=-1;
public ExtendedTabbedPageRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.TabbedPage> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
tabbedPage = e.NewElement as ExtendedTabbedPage;
bottomNavigationView = (GetChildAt(0) as Android.Widget.RelativeLayout).GetChildAt(1) as BottomNavigationView;
//Call to change the font
ChangeFont();
}
}
//Change Tab font
void ChangeFont()
{
var fontFace = Typeface.CreateFromAsset(Context.Assets, "gilsansultrabold.ttf");
var bottomNavMenuView = bottomNavigationView.GetChildAt(0) as BottomNavigationMenuView;
for (int i = 0; i < bottomNavMenuView.ChildCount; i++)
{
var item = bottomNavMenuView.GetChildAt(i) as BottomNavigationItemView;
var itemTitle = item.GetChildAt(1);
var smallTextView = ((TextView)((BaselineLayout)itemTitle).GetChildAt(0));
var largeTextView = ((TextView)((BaselineLayout)itemTitle).GetChildAt(1));
lastItemId = bottomNavMenuView.SelectedItemId;
//smallTextView.SetTypeface(fontFace, TypefaceStyle.Bold);
//largeTextView.SetTypeface(fontFace, TypefaceStyle.Bold);
smallTextView.TextSize = 18;
largeTextView.TextSize = 18;
//Set text color
var textColor = (item.Id == bottomNavMenuView.SelectedItemId) ? tabbedPage.On<Xamarin.Forms.PlatformConfiguration.Android>().GetBarSelectedItemColor().ToAndroid() : tabbedPage.On<Xamarin.Forms.PlatformConfiguration.Android>().GetBarItemColor().ToAndroid();
smallTextView.SetTextColor(textColor);
largeTextView.SetTextColor(textColor);
}
}
}
}
If you want to add border line for tabbar, please take a look this thread:
Xamarin Tab Bar top(border) line

Related

How to create a Xamarin Tooltip in code-behind

I am testing using the following example. https://github.com/CrossGeeks/TooltipSample
The sample works fine, it even works with Labels (sample uses buttons, images and boxviews). The issue is in my main App I need to create the tooltips in code behind.
To test how to do it, in the very same solution (from that above example) I created a TestPage and made it my MainPage in App.xaml.cs. The XAML looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ToolTipSample.TestPage">
<ContentPage.Content>
<StackLayout
x:Name="mainLayout"
BackgroundColor="Yellow">
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Tapped="Handle_Tapped"/>
</StackLayout.GestureRecognizers>
</StackLayout>
</ContentPage.Content>
The code-behind looks like this:
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using ToolTipSample.Effects;
namespace ToolTipSample
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class TestPage : ContentPage
{
public TestPage()
{
InitializeComponent();
var actionLabel = new Label
{
Text = "Show Tooltip",
WidthRequest = 150,
VerticalOptions = LayoutOptions.StartAndExpand,
HorizontalOptions = LayoutOptions.Center,
BackgroundColor = Color.Wheat
};
// Add tooltip to action label
TooltipEffect.SetPosition(actionLabel, TooltipPosition.Bottom);
TooltipEffect.SetBackgroundColor(actionLabel, Color.Silver);
TooltipEffect.SetTextColor(actionLabel, Color.Teal);
TooltipEffect.SetText(actionLabel, "This is the tooltip");
TooltipEffect.SetHasTooltip(actionLabel, true);
actionLabel.Effects.Add(Effect.Resolve($"CrossGeeks.{nameof(TooltipEffect)}"));
mainLayout.Children.Add(actionLabel);
}
void Handle_Tapped(object sender, System.EventArgs e)
{
foreach (var c in mainLayout.Children)
{
if (TooltipEffect.GetHasTooltip(c))
{
TooltipEffect.SetHasTooltip(c, false);
TooltipEffect.SetHasTooltip(c, true);
}
}
}
}
}
All other code unchanged.
When I tap the label, the tooltip appears as expected. But when I tap the background it does not disappear (like those created in XAML in the sample).
One other thing. If I tap twice it disappears.
Can anyone see what I am missing?
Thanks.
According to your description and code, you can delete the following line code to achieve your requirement.
actionLabel.Effects.Add(Effect.Resolve($"CrossGeeks.{nameof(TooltipEffect)}"));
You don't need to add effect for control when page load, because this effect will be added when you click this control by these code:
static void OnHasTooltipChanged(BindableObject bindable, object oldValue, object newValue)
{
var view = bindable as View;
if (view == null)
{
return;
}
bool hasTooltip = (bool)newValue;
if (hasTooltip)
{
view.Effects.Add(new ControlTooltipEffect());
}
else
{
var toRemove = view.Effects.FirstOrDefault(e => e is ControlTooltipEffect);
if (toRemove != null)
{
view.Effects.Remove(toRemove);
}
}
}

In Xamarin.Forms how to set a popup page in desired position using RG.Plugin?

I installed the Nuget package Rg.plugins.popup.
Tried to set a popup page that should appear on right.
Tried different ways but not able find a solution
<pages:PopupPage.Animation>
<animations:MoveAnimation
PositionIn="Right"
PositionOut="Right"
DurationIn="300"
DurationOut="300"
EasingIn="SinOut"
EasingOut="SinIn"
HasBackgroundAnimation="True"/>
</pages:PopupPage.Animation>
Any solution with RG plugin?
It's not about the animation, that will only control the appearance. You should make sure the content of the popup page is properly arranged. For instance, here is the XAML for a popup page that will display a square popup in the top right corner.
<?xml version="1.0" encoding="UTF-8"?>
<pages:PopupPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"
xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations;assembly=Rg.Plugins.Popup"
x:Class="MyApp.Views.RandomPopupPage">
<StackLayout
BackgroundColor="White"
HorizontalOptions="End"
VerticalOptions="Start"
Margin="20"
WidthRequest="100"
HeightRequest="100"
Spacing="0">
<Label
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center"
VerticalOptions="Center"
HorizontalOptions="Center"
Text="Some text here" />
</StackLayout>
</pages:PopupPage>
It has a StackLayout vertically aligned with start (TOP) and horizontally aligned with end (right). It also has a fixed width and height. You should arrange its elements as you do with a normal page keeping in mind it has a transparent background.
It looks like this: See image
Tried to set a popup page that should appear on right.
From Rg.plugins.popup document , can custom animations as follow:
Creat UserAnimation class
class UserAnimation : MoveAnimation
{
private double _defaultTranslationY;
public UserAnimation()
{
DurationIn = DurationOut = 300;
EasingIn = Easing.SinOut;
EasingOut = Easing.SinIn;
PositionIn = MoveAnimationOptions.Right;
PositionOut = MoveAnimationOptions.Right;
}
//1
public override void Preparing(View content, PopupPage page)
{
base.Preparing(content, page);
page.IsVisible = false;
if (content == null) return;
_defaultTranslationY = content.TranslationY;
}
//3
public override void Disposing(View content, PopupPage page)
{
base.Disposing(content, page);
page.IsVisible = true;
if (content == null) return;
content.TranslationY = _defaultTranslationY;
}
//2
public async override Task Appearing(View content, PopupPage page)
{
var taskList = new List<Task>();
taskList.Add(base.Appearing(content, page));
if (content != null)
{
var topOffset = GetTopOffset(content, page);
var leftOffset = GetLeftOffset(content, page);
taskList.Add(content.TranslateTo(content.Width, _defaultTranslationY, DurationIn, EasingIn));
};
page.IsVisible = true;
await Task.WhenAll(taskList);
}
//4
public async override Task Disappearing(View content, PopupPage page)
{
var taskList = new List<Task>();
taskList.Add(base.Disappearing(content, page));
if (content != null)
{
_defaultTranslationY = content.TranslationX - content.Width;
var topOffset = GetTopOffset(content, page);
var leftOffset = GetLeftOffset(content, page);
taskList.Add(content.TranslateTo(leftOffset, _defaultTranslationY, DurationOut, EasingOut));
};
await Task.WhenAll(taskList);
}
}
Use it in Xaml:
<pages:PopupPage.Animation>
<animations:UserAnimation/>
</pages:PopupPage.Animation>
Not sure if the effect below is what you want, but you can use this method to customize the animation.

How to change searchbar cancel button image in xamarin forms

I have used custom renderer to change the search bar underline color. But i don't know how to change the cancel button cross symbol(X) to image as shown in the attached screenshot. My custom renderer is as below,
public class CustomSearchBarRenderer : SearchBarRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
{
base.OnElementChanged(e);
if (e.OldElement == null)
{
LinearLayout linearLayout = this.Control.GetChildAt(0) as LinearLayout;
linearLayout = linearLayout.GetChildAt(2) as LinearLayout;
linearLayout = linearLayout.GetChildAt(1) as LinearLayout;
GradientDrawable gd = new GradientDrawable();
gd.SetStroke(0, Android.Graphics.Color.LightGray);
linearLayout.Background = gd;
AutoCompleteTextView textView = linearLayout.GetChildAt(0) as AutoCompleteTextView;
}
}
}
How to change searchbar cancel button image in xamarin forms
Modify your code like this :
public class MySearchBarRenderer : SearchBarRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.SearchBar> e)
{
base.OnElementChanged(e);
if (Control != null)
{
var searchView = Control;
int searchViewCloseButtonId = Control.Resources.GetIdentifier("android:id/search_close_btn", null, null);
var closeIcon = searchView.FindViewById(searchViewCloseButtonId);
(closeIcon as ImageView).SetImageResource(Resource.Drawable.cancel_icon);
}
}
}
Effect.
You can use renderer like this for your code
using System;
using Android.Content;
using Android.Graphics.Drawables;
using Android.Support.V4.Content;
using Android.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using CustomRenderers
[assembly: ExportRenderer(typeof(SearchBar), typeof(CustomSearchBarRenderer))]
namespace CustomRenderers
{
public class CustomSearchBarRenderer : SearchBarRenderer
{
Context context;
public CustomSearchBarRenderer(Context context) : base(context)
{
this.context = context;
}
protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
{
base.OnElementChanged(e);
if (Control == null)
{
return;
}
if (e.OldElement == null)
{
//remove the underline line of the edittext
LinearLayout linearLayout = this.Control.GetChildAt(0) as LinearLayout;
linearLayout = linearLayout?.GetChildAt(2) as LinearLayout;
linearLayout = linearLayout?.GetChildAt(1) as LinearLayout;
if (linearLayout != null)
{
//set transparent to remove the underline line of edittext
linearLayout.SetBackground(new ColorDrawable(Android.Graphics.Color.Transparent));
}
}
//set rounded background
Control.Background = ContextCompat.GetDrawable(Context, Resource.Drawable.RoundedSearchViewRectangle);
//abc_ic_clear_material is system clear icon which is in gray color
ImageView searchClose = (ImageView)Control.FindViewById(context.Resources.GetIdentifier("android:id/search_close_btn", null, null));
searchClose?.SetImageResource(Resource.Drawable.abc_ic_clear_material);
}
}
}
this is the Resources\Drawable\RoundedSearchViewRectangle.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="20dp" />
<solid android:color="#ffff80" />
</shape>
Before apply this code, we have
it will looks like this before and after apply these code:
and you can change the icon of it with this code
searchClose?.SetImageResource(Resource.Drawable.ic_stop);
it will looks like this
If you want a clear button with gray circle around it, you can set background:
searchClose.SetBackgroundResource(Resource.Drawable.SearchViewClearButton);
Resources\Drawable\SearchViewClearButton.xml
<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape
android:innerRadius="0dp"
android:shape="ring"
android:thickness="12dp"
android:useLevel="false">
<solid android:color="#a9a9a9" />
</shape>
</item>
</layer-list>
and it will look like this:
If you want to hide the cancel button, you can use this code
Control.ShowsCancelButton = false;

Xamarin Forms - finding databound object from custom renderer while responding to a swipe

From an iOS swipe event, I am trying to figure out how to work my way back to the model databound to the ViewCell (model is my own Drive object, a simple POCO).
I am using a subclassed StackLayout ...
public class MainPageStackLayout : StackLayout { }
with a custom renderer...
[assembly: ExportRenderer(typeof(MainPageStackLayout), typeof(MainPageStackLayoutRenderer))]
namespace DriveLive.iOS
{
public class MainPageStackLayoutRenderer : VisualElementRenderer<StackLayout>
{
UISwipeGestureRecognizer swipeGestureRecognizer;
protected override void OnElementChanged(ElementChangedEventArgs<StackLayout> e)
{
base.OnElementChanged(e);
swipeGestureRecognizer = new UISwipeGestureRecognizer(() =>
{
//********************
Console.WriteLine("How to access the underlying model here?");
//********************
}) { Direction = UISwipeGestureRecognizerDirection.Left, NumberOfTouchesRequired = 1 };
if (e.NewElement == null)
{
if (swipeGestureRecognizer != null)
this.RemoveGestureRecognizer(swipeGestureRecognizer);
}
if (e.OldElement == null)
{
this.AddGestureRecognizer(swipeGestureRecognizer);
}
}
}
}
and the code that uses the MainPageStackLayout ...
<?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:DriveLive"
x:Class="DriveLive.Views.MainPage">
<ListView x:Name="___drives" HasUnevenRows="True">
<ListView.ItemTemplate />
</ListView>
</ContentPage>
C#
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
IDriveRespository repo = new DriveLive.Repository.Fakes.DriveRespository();
___drives.ItemsSource = repo.GetDrivesForUser(45); // returns a Drive list of objects
___drives.ItemTemplate = new DataTemplate(typeof(CustomViewCell));
___drives.SeparatorColor = Color.FromHex("#81C1B5");
}
}
public class CustomViewCell : ViewCell
{
bool _initialized = false;
StackLayout _cellStack;
public CustomViewCell()
{
_cellStack = new MainPageStackLayout()
{
Orientation = StackOrientation.Vertical,
HorizontalOptions = LayoutOptions.FillAndExpand
};
View = _cellStack;
var label = new Label() { FontAttributes = FontAttributes.Bold };
label.SetBinding(Label.TextProperty, new Binding("DestinationName"));
_cellStack.Children.Add(label);
}
}
From the handler for the UISwipeGestureRecognizer, how can I access the underlying Drive object which is databound to the ViewCell?
My issue is resolved by leveraging this piece of XForms.
ListView Interactivity - Context Actions
Credit goes to #skar's comment for pointing me in the right direction.

Xamarin WebView scale to fit

Is there a way to set a WebView in Xamarin to scale its content to fit the screen by default and still allow for pinch zooming in/out?
We're going to use this to display documents we have online.
I solved the scale fit to page and zooming by Custom Renderers, as given below
For IOS
public class CustomWebViewRenderer : WebViewRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
var view = Element as CustomWebView;
if (view == null || NativeView == null)
{
return;
}
this.ScalesPageToFit = true;
}
}
For Android
public class CustomWebViewRenderer : WebViewRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.Settings.BuiltInZoomControls = true;
Control.Settings.DisplayZoomControls = false;
Control.Settings.LoadWithOverviewMode = true;
Control.Settings.UseWideViewPort = true;
}
}
}
If you're using Xamarin.Forms that would look something like this
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="WebViewDemo.LoadingDemo" Title="Loading Demo">
<ContentPage.Content>
<StackLayout>
<WebView x:Name="Browser"
VerticalOptions = LayoutOptions.FillAndExpand ,
HorizontalOptions = LayoutOptions.FillAndExpand,
</StackLayout>
</ContentPage.Content>
</ContentPage>
This should fill the page and not affect pinch and zoom.

Resources