I have used MasterDetail page as main page of my app. Here TabbedPage is my detail page which contain various ContentPage as children of TabbedPage. I have set Details as Detail = NavigationPage(tabbedpage); it work great for IOS but in android it occupie more space in NavigationBar title and Tabbed Name, I cannot omit both, my question is how can i reduce the height of title bar of navigation page.
Please check attached image for reference.
You need to set padding platform specific for example.
<OnPlatform x:TypeArguments="FontAttributes" x:Key="fontAttributes">
<OnPlatform.iOS>Bold</OnPlatform.iOS>
<OnPlatform.Android>Italic</OnPlatform.Android>
</OnPlatform>
You need to implement a CustomNavigationPage with a Custom renderer. Refer this - https://xamgirl.com/transparent-navigation-bar-in-xamarin-forms/
<?xml version="1.0" encoding="utf-8" ?>
<NavigationPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="TransparentNavBarXForms.CustomNavigationPage"
BarTextColor="White">
<NavigationPage.BarBackgroundColor>
<OnPlatform x:TypeArguments="Color">
<On Platform="Android, iOS" Value="Transparent" />
</OnPlatform>
</NavigationPage.BarBackgroundColor>
</NavigationPage>
public partial class CustomNavigationPage : NavigationPage
{
public CustomNavigationPage() : base()
{
InitializeComponent();
}
public CustomNavigationPage(Page root) : base(root)
{
InitializeComponent();
}
public bool IgnoreLayoutChange { get; set; } = false;
protected override void OnSizeAllocated(double width, double height)
{
if (!IgnoreLayoutChange)
base.OnSizeAllocated(width, height);
}
}
public class CustomNavigationPageRenderer : NavigationPageRenderer
{
public CustomNavigationPageRenderer(Context context) : base(context)
{
}
IPageController PageController => Element as IPageController;
CustomNavigationPage CustomNavigationPage => Element as CustomNavigationPage;
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
CustomNavigationPage.IgnoreLayoutChange = true;
base.OnLayout(changed, l, t, r, b);
CustomNavigationPage.IgnoreLayoutChange = false;
int containerHeight = b - t;
PageController.ContainerArea = new Rectangle(0, 0, Context.FromPixels(r - l), Context.FromPixels(containerHeight));
for (var i = 0; i < ChildCount; i++)
{
AView child = GetChildAt(i);
if (child is Android.Support.V7.Widget.Toolbar)
{
continue;
}
child.Layout(0, 0, r, b);
}
}
}
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new CustomNavigationPage(new MainPage());
}
}
Related
I have a xamarin forms application and I have inserted a webview inside the layout stack, the problem is that I have multiple pages and in each page the length of the content is different from the others.
I wanted to ask if there was a way to have the webview automatically adjust the height.
I have read other similar questions on the site, but I admit they seemed confusing to me.
This is my code xaml
<ContentPage.Content>
<StackLayout Padding="0" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Spacing="0" BackgroundColor="White">
<WebView
x:Name="wvSite"
VerticalOptions="FillAndExpand"
HeightRequest="2300" />
</StackLayout>
</ContentPage.Content>
You could reset the webview height according to the content height when loading page finished via custom renderer.
Android:
[assembly: ExportRenderer(typeof(WebView), typeof(CustomWebViewRenderer))]
namespace App1.Droid
{
public class CustomWebViewRenderer : WebViewRenderer
{
public CustomWebViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
Control.SetWebViewClient(new CustomWebViewClient(e.NewElement));
}
}
internal class CustomWebViewClient : Android.Webkit.WebViewClient
{
private WebView webView;
public CustomWebViewClient(WebView webView)
{
this.webView = webView;
}
public async override void OnPageFinished(Android.Webkit.WebView view, string url)
{
if (webView != null)
{
int i = 10;
while (view.ContentHeight == 0 && i-- > 0)
await System.Threading.Tasks.Task.Delay(100);
webView.HeightRequest = view.ContentHeight;
}
base.OnPageFinished(view, url);
}
}
}
iOS:
[assembly: ExportRenderer(typeof(WebView),
typeof(CustomWebviewRenderer))]
namespace App1.iOS
{
public class CustomWebviewRenderer : WkWebViewRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
NavigationDelegate = new CustomWebviewNavigationDelegate();
}
}
internal class CustomWebviewNavigationDelegate : WKNavigationDelegate
{
[Export("webview:didFinishNavigation:")]
public override void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
{
//base.DidFinishNavigation(webView, navigation);
webView.Frame = new CoreGraphics.CGRect(0, 0, webView.ScrollView.ContentSize.Width, webView.ScrollView.ContentSize.Height);
}
}
}
I created a Master-Detail type project in Xamarin. When I selected an item from the Master page the background color is orange by default. How can I change this to a color of my choosing?
You can bind BackgroundColor for ContentView of ViewCell , then use ViewModel and ItemTapped method of ListView to modify the selected item background color .
For example , the xaml code as follow:
<ListView x:Name="ListViewMenu"
HasUnevenRows="True" ItemTapped="ListViewMenu_ItemTapped">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell >
<Grid Padding="10"
BackgroundColor="{Binding SelectedBackgroundColor}">
<Label Text="{Binding Title}" d:Text="{Binding .}" FontSize="20"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Then in HomeMenuItem model add SelectedBackgroundColor property :
public enum MenuItemType
{
Browse,
About
}
public class HomeMenuItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public MenuItemType Id { get; set; }
public string Title { get; set; }
private Color selectedBackgroundColor;
public Color SelectedBackgroundColor
{
set
{
if (selectedBackgroundColor != value)
{
selectedBackgroundColor = value;
OnPropertyChanged("SelectedBackgroundColor");
}
}
get
{
return selectedBackgroundColor;
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Then in MenuPage modify ItemSource as follow:
public partial class MenuPage : ContentPage
{
MainPage RootPage { get => Application.Current.MainPage as MainPage; }
List<HomeMenuItem> menuItems;
List<HomeMenuItem> tmpItems; // add a tmp list to remove setted backgroud color
public MenuPage()
{
InitializeComponent();
tmpItems = new List<HomeMenuItem>();
menuItems = new List<HomeMenuItem>
{
new HomeMenuItem {Id = MenuItemType.Browse, Title="Browse" },
new HomeMenuItem {Id = MenuItemType.About, Title="About" }
};
menuItems[0].SelectedBackgroundColor = Color.Red; // default set the first item be selected, you can modify as your wants
tmpItems.Add(menuItems[0]); // add the selected item (default is the first)
ListViewMenu.ItemsSource = menuItems;
ListViewMenu.SelectedItem = menuItems[0];
ListViewMenu.ItemSelected += async (sender, e) =>
{
if (e.SelectedItem == null)
return;
var id = (int)((HomeMenuItem)e.SelectedItem).Id;
await RootPage.NavigateFromMenu(id);
};
}
private void ListViewMenu_ItemTapped(object sender, ItemTappedEventArgs e)
{
menuItems[e.ItemIndex].SelectedBackgroundColor = Color.Red;
tmpItems[0].SelectedBackgroundColor = Color.Transparent;
tmpItems[0] = menuItems[e.ItemIndex];
}
}
The effect :
This problem is specific to Android. In the Android project add this line to Resources\values\styles.xml inside the <style> tag:
<item name="android:colorActivatedHighlight">#00FFFFFF</item>
I am working on a Xamarin.Forms application, and I want to set the height of a webview dynamically as pet text in uwp platform.
Define a Custom Renderer for your webview and then inject a javascript to calculate the content's size:
[assembly: ExportRenderer(typeof(CustomWebView), typeof(MyWebViewRenderer))]
namespace Demo.UWP
{
public class MyWebViewRenderer : WebViewRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.NavigationCompleted += Control_NavigationCompleted;
}
}
private async void Control_NavigationCompleted(Windows.UI.Xaml.Controls.WebView sender, Windows.UI.Xaml.Controls.WebViewNavigationCompletedEventArgs args)
{
var heightString = await Control.InvokeScriptAsync("eval", new[] { "document.body.scrollHeight.toString()" });
int height;
if (int.TryParse(heightString, out height))
{
Element.HeightRequest = height;
}
}
}
}
Your Forms page's Xaml could be like:
<ScrollView>
<StackLayout>
<local:CustomWebView Source="https://www.microsoft.com"/>
<!--Other controls-->
</StackLayout>
</ScrollView>
There is something different between the default WebViewRenderer and my custom ViewRenderer and I have to find out why. Basically, the web page isn't displayed if I use my custom ViewRenderer.
The ViewRenderer has some issues with height: 100%; and interprets this CSS wrong. As result the height is 0px, despite it should use the full height. On the other side it works with exact sizes (e.g. 400px).
Code for WebViewRenderer:
<local:CustomWebView x:Name="webView"
Source="http://somesite"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"
HeightRequest="1000"
WidthRequest="1000"/>
public class CustomWebView : WebView
{
}
public class CustomWebViewRenderer : WebViewRenderer
{
public CustomWebViewRenderer(Context context) : base(context)
{
}
}
Code for ViewRenderer:
<local:HybridWebView x:Name="webView"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"
HeightRequest="1000"
WidthRequest="1000"/>
public class HybridWebView : View
{
}
public class HybridWebViewRenderer : ViewRenderer<HybridWebView, Android.Webkit.WebView>
{
private Context context;
public HybridWebViewRenderer(Context context) : base(context)
{
this.context = context;
}
protected override void OnElementChanged(ElementChangedEventArgs<HybridWebView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
var webView = new Android.Webkit.WebView(this.context);
webView.Settings.JavaScriptEnabled = true;
webView.SetWebViewClient(new CustomWebViewClient());
SetNativeControl(webView);
}
if (e.OldElement != null)
{
}
if (e.NewElement != null)
{
Control.LoadUrl("http://somesite");
}
}
}
public class CustomWebViewClient : WebViewClient
{
}
One assumption is that the responsive website adapts to its WebView size, and since the rendering process takes place in background it somehow has a height of zero at this time.
I don't know why, but this solves the issue for me:
webView.LayoutParameters = new LinearLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent);
If anyone has a clue, please comment.
I have the following code for my custom renderer. The Element in use is a Label and I'm trying to set a background colour with rounded edges.
[assembly: ExportRenderer(typeof(RoundedLabel), typeof(RoundedLabelCustomRenderer))]
namespace MyNamespace.UWP.CustomRenderers
{
public class RoundedLabelCustomRenderer : LabelRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
var view = (RoundedLabel)e.NewElement;
Children.Clear();
var border = new Border
{
CornerRadius = new CornerRadius(view.RoundedCornerRadius),
Background = new SolidColorBrush(view.RoundedBackgroundColor.ToWindows()),
Child = Control
};
Control.Padding = new Windows.UI.Xaml.Thickness(
view.InsidePadding.Left,
view.InsidePadding.Top,
view.InsidePadding.Right,
view.InsidePadding.Bottom);
Control.Foreground = new SolidColorBrush(view.TextColor.ToWindows());
Children.Add(border);
}
}
}
}
For the likes of a button (which is a composite object in UWP), this would be fine and if it was in "pure" XAML, something like
<Border background="gray" cornerradius="12">
<TextBlock />
</Border>
would do the job.
I'm just having fun and games trying to reconcile the two snippets together.
Any pointers to what I'm doing wrong would be appreciated.
It is difficult to realize your requirement with custom LabelRenderer. Because there is no such interface to modify background color and Radius. However, you can do that via custom View. And then in UWP client project you could use UserControl to render the control you want.
CustomNewLabelControl.cs
public class CustomNewLabelControl : View
{
public static readonly BindableProperty LabelTextProperty = BindableProperty.Create(
propertyName: "LabelText",
eturnType: typeof(string),
declaringType: typeof(CustomNewLabelControl),
defaultValue: default(string));
public string LabelText
{
get { return (string)GetValue(LabelTextProperty); }
set { SetValue(LabelTextProperty, value); }
}
public static readonly BindableProperty LabelRadiusProperty = BindableProperty.Create(
propertyName: "LabelRadius",
eturnType: typeof(double),
declaringType: typeof(CustomNewLabelControl),
defaultValue: default(double));
public double LabelRadius
{
get { return (double)GetValue(LabelRadiusProperty); }
set { SetValue(LabelRadiusProperty, value); }
}
public static readonly BindableProperty LabelBackgroundProperty = BindableProperty.Create(
propertyName: "LabelBackground",
eturnType: typeof(Color),
declaringType: typeof(CustomNewLabelControl),
defaultValue: default(Color));
public Color LabelBackground
{
get { return (Color)GetValue(LabelBackgroundProperty); }
set { SetValue(LabelBackgroundProperty, value); }
}
}
NewLabelControl.xaml.cs
public sealed partial class NewLabelControl : UserControl
{
public NewLabelControl()
{
this.InitializeComponent();
this.DataContext = this;
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(NewLabelControl), new PropertyMetadata(0));
public SolidColorBrush LabelBackground
{
get { return (SolidColorBrush)GetValue(LabelBackgroundProperty); }
set { SetValue(LabelBackgroundProperty, value); }
}
public static readonly DependencyProperty LabelBackgroundProperty =
DependencyProperty.Register("LabelBackground", typeof(SolidColorBrush), typeof(NewLabelControl), new PropertyMetadata(0));
public CornerRadius LabelRadius
{
get { return (CornerRadius)GetValue(LabelRadiusProperty); }
set { SetValue(LabelRadiusProperty, value); }
}
public static readonly DependencyProperty LabelRadiusProperty =
DependencyProperty.Register("LabelRadius", typeof(CornerRadius), typeof(NewLabelControl), new PropertyMetadata(0));
public SolidColorBrush LabelForeground
{
get { return (SolidColorBrush)GetValue(LabelForegroundProperty); }
set { SetValue(LabelForegroundProperty, value); }
}
public static readonly DependencyProperty LabelForegroundProperty =
DependencyProperty.Register("LabelForeground", typeof(SolidColorBrush), typeof(NewLabelControl), new PropertyMetadata(0));
}
NewLabelControl.xaml
<Grid>
<Border CornerRadius="{Binding LabelRadius}" Background="{Binding LabelBackground}">
<TextBlock Text="{Binding Text}" Foreground="{Binding LabelForeground }" />
</Border>
</Grid>
CustomNewLabelRanderer.cs
internal class CustomNewLabelRanderer : ViewRenderer<CustomNewLabelControl, NewLabelControl>
{
protected override void OnElementChanged(ElementChangedEventArgs<CustomNewLabelControl> e)
{
base.OnElementChanged(e);
if (Control == null)
{
SetNativeControl(new NewLabelControl());
}
if (e.OldElement != null)
{
}
if (e.NewElement != null)
{
Control.Text = Element.LabelText;
Control.LabelRadius = new Windows.UI.Xaml.CornerRadius(Element.LabelRadius);
Color color = Element.LabelBackground;
Control.LabelBackground = new Windows.UI.Xaml.Media.SolidColorBrush(
Windows.UI.Color.FromArgb(
(byte)(color.A * 255),
(byte)(color.R * 255),
(byte)(color.G * 255),
(byte)(color.B * 255)));
}
}
}
Usage
<local:CustomNewLabelControl LabelText="Welcome to Xamarin Forms!"
LabelBackground="Gray" LabelRadius="5"
VerticalOptions="Center"
HorizontalOptions="Center" />
What you're probably looking for is Frame (which actually is rendered as a Border on UWP). Frame let's you set both background color and corner radius:
<Frame BackgroundColor="Grey" CornerRadius="12" HasShadow="false" Padding="0">
<Label />
</Frame>
Frame has a drop shadow and padding set to 20 by default, so you'll have to removed those for your desired result.