On Xamarin.Forms (iOS Android), I need to change the loading-indicator position on the RefreshView. I need to add offset, so the indicator is visible if you have a bar overlapping the ScrollView-RefreshView combo and trigger pullOnRefresh.
Loading-indicator in the top edge
EDIT: thanks to Junior Jiang - MSFT- Android solution
I also implement a solution for xamarin.iOS
[assembly: ExportRenderer(typeof(RefreshView), typeof(CustomRefreshViewRenderer))]
namespace CustomRefresh.iOS {
public class CustomRefreshViewRenderer : RefreshViewRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<RefreshView> e)
{
base.OnElementChanged(e);
foreach (var nativeView in Subviews)
updateRefreshSettings(nativeView);
}
void updateRefreshSettings(UIView view) {
if (view is UIScrollView)
{
var scrollView = view as UIScrollView;
if (scrollView.RefreshControl != null)
{
var bounds = scrollView.RefreshControl.Bounds;
scrollView.RefreshControl.Bounds = new CGRect(bounds.X, -(100), bounds.Width, bounds.Height);
}
}
//add more scrollable view types
}
}
}
You can custom a RefreshViewRenderer to achieve that .
In Android , there is a MOriginalOffsetTop to modify the offset of loading indicator . In addition , also can use SetProgressViewOffset to set the start and end position of indicator .
Code as follow :
using Android.Content;
using RefreshViewDemo.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(RefreshView), typeof(CustomRefreshViewRenderer))]
namespace RefreshViewDemo.Droid
{
public class CustomRefreshViewRenderer : RefreshViewRenderer
{
public CustomRefreshViewRenderer(Context context) : base(context)
{
MOriginalOffsetTop = 100;
// SetProgressViewOffset(true, 100, 101);
}
}
}
In iOS , the loading indicator belong to UIRefreshControl of UIScrollView , there is no direct way to change it's offset . Unless override all content view in Renderer then can achieve that . You can refer this Xamarin.Forms/Xamarin.Forms.Platform.iOS/Renderers/RefreshViewRenderer.cs to know what the RefreshView is made of .
====================Update=====================
Shared code is based on this official sample :https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/userinterface-refreshviewdemo/
For Android , just need to create a CustomRefreshViewRenderer class in android solution .
The effect of SetProgressViewOffset(true, 100, 101) , it seems like the indicator not moving :
Related
I'm creating an app using xamarin Forms (multiplatform), I'm using a Navigation page, but I want to change the arrow ("<-") to text ("back")
Do you know how could i do it?
Thanks
(I'm going to use it in an Android App, but I'm creating the app using Xamarin forms)
You could use custom renderer to remove the navigation icon and set it with text. But, when you do that, you need to capture the click of the text and simulate the back event.
Create the interface:
public class CustomNavigationPage : NavigationPage
{
public CustomNavigationPage(Page startupPage) : base(startupPage)
{
}
}
The implementation of Android:
[assembly: ExportRenderer(typeof(CustomNavigationPage),
typeof(NavigationPageRenderer_Droid))]
namespace NavigationPageDemo.Droid
{
public class NavigationPageRenderer_Droid : NavigationPageRenderer
{
public Android.Support.V7.Widget.Toolbar toolbar;
public Activity context;
public NavigationPageRenderer_Droid(Context context) : base(context)
{
}
protected override Task<bool> OnPushAsync(Page view, bool animated)
{
var retVal = base.OnPushAsync(view, animated);
context = (Activity)Forms.Context;
toolbar = context.FindViewById<Android.Support.V7.Widget.Toolbar>(Droid.Resource.Id.toolbar);
if (toolbar != null)
{
//if (toolbar.NavigationIcon != null)
//{
//toolbar.NavigationIcon = Android.Support.V7.Content.Res.AppCompatResources.GetDrawable(context, Resource.Drawable.back);
//toolbar.NavigationIcon = null;
toolbar.NavigationIcon = null;
toolbar.Title = "back";
toolbar.SetOnClickListener(new OnClick());
//}
}
return retVal;
}
protected override Task<bool> OnPopViewAsync(Page page, bool animated)
{
return base.OnPopViewAsync(page, animated);
}
}
public class OnClick : Java.Lang.Object, IOnClickListener
{
void IOnClickListener.OnClick(Android.Views.View v)
{
App.Current.MainPage.Navigation.PopAsync();
}
}
In the custom renderer, use the OnClickListener to capture the click on text.
when you are working with xamarin forms it is suggested make use of common components and make least use of custom renderer.
Now for your requirement you want to create custom navigation bar
so here is how you can do it.
Create BaseContent Page
Create a Control Template inside your base page your can follow this link
Inside your control template using a grid view place your label with text binding (Back),also your can place a label in center to show title of page again u can make use of template binding which u would come to know when u go through the link
Now inherit your main page with your basecontentpage page
add your control template inside your main page
turn off your navigation bar of your main page
and you are done, this would give u more power to add more things like image or toolbar in your navbar
also to dynamically handle your back button u can check the count from navigationstack if its 0 u can show Humburger Icon or if its more than 0 u can show your label using IsVisible True/False
I need to display native controller IOS from Xamarin.forms I have tried this
UIWindow window = UIApplication.SharedApplication.KeyWindow;
UIViewController vc = window.RootViewController;
RGLDocReader.Shared.ShowScanner(vc, HandleRGLDocumentReaderCompletion);
this
How to create navigation in a Xamarin.iOS app?
followed this
https://learn.microsoft.com/en-us/xamarin/ios/app-fundamentals/ios-code-only?tabs=macos
the tutorial works fine, however I need to use view controller in the method as that is specified and once I pass view controller I get null
Actually , it is not a good design to navigate to a native controller in Forms . But if you do want to implement it , you could use DependencyService .
in Forms
Create the interface
public interface IOpenNativeView
{
void OpenNativeView();
}
in iOS project
using xxx.iOS;
using Foundation;
using UIKit;
using Xamarin.Forms;
[assembly: Dependency(typeof(OpenNativeView))]
namespace xxx.iOS
{
public class OpenNativeView : IOpenNativeView
{
void IOpenNativeView.OpenNativeView()
{
var CurrentViewController = topViewControllerWithRootViewController(UIApplication.SharedApplication.Delegate.GetWindow().RootViewController);
CurrentViewController.NavigationController.PushViewController(YourViewController,true);
}
UIViewController topViewControllerWithRootViewController(UIViewController rootViewController)
{
if (rootViewController is UITabBarController)
{
UITabBarController tabBarController = (UITabBarController)rootViewController;
return topViewControllerWithRootViewController(tabBarController.SelectedViewController);
}
else if (rootViewController is UINavigationController)
{
UINavigationController navigationController = (UINavigationController)rootViewController;
return topViewControllerWithRootViewController(navigationController.VisibleViewController);
}
else if (rootViewController.PresentedViewController != null)
{
UIViewController presentedViewController = rootViewController.PresentedViewController;
return topViewControllerWithRootViewController(presentedViewController);
}
else
{
return rootViewController;
}
}
}
}
Now in the ContentPage you can invoke the following line when you want to open the ViewController
DependencyService.Get<IOpenNativeView>().OpenNativeView();
I would like to extend all the contentpages in my xamarin.forms app with a native view in UWP. I can basically go to each and every page and embed a native view but i dont want this. I want to know if there is a way to do it using a pagerenderer. I tried doing like below.
my idea was to get current page rendering and extend the content with native view and stacklayout and define app.content again with this change. It works in general. If you run the small test project below, you can see that native UWP FontIcons are displayed for each page but there is a problem, if i navigate same page 2 times in MasterDetail in the attached project, page becomes blank. Why is this happening?
and is the approach below best for my case? I am open for alternative solutions.
[assembly: ExportRenderer(typeof(ContentPage), typeof(App3.UWP.ContentPageRenderer))]
namespace App3.UWP
{
public class ContentPageRenderer : PageRenderer
{
bool isDisposing = false;
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Page> e)
{
base.OnElementChanged(e);
if (isDisposing)
return;
if (e.OldElement != null || Element == null)
{
return;
}
ContentPage page = ((ContentPage)Element);
if (page.Content == null)
return;
var XboxControls = new MyUserControl1();
StackLayout stackLayout = new StackLayout() { Orientation = StackOrientation.Vertical };
stackLayout.Children.Add(page.Content);
stackLayout.Children.Add(XboxControls.ToView());
page.Content = stackLayout;
}
protected override Windows.Foundation.Size ArrangeOverride(Windows.Foundation.Size finalSize)
{
return base.ArrangeOverride(finalSize);
}
protected override void Dispose(bool disposing)
{
isDisposing = disposing;
base.Dispose(disposing);
}
}
Test Project
I'm using new forms feature Right-to-Left, it works well except MasterDetail hamburger menu icon. It stays on the left side and I need to move it to right whem localization is changed. Any ideas or could somebody help me with custom renderer?
well not impossible but some dirty coding is needed:
please check the solution here
as recap:
To force the layout RTL and LTR on IOS:
1- Create this class/service
using System;
using System.IO;
using Xamarin.Forms;
using yourproject.iOS;
using yourproject.database;
using ObjCRuntime;
using System.Runtime.InteropServices;
using UIKit;
using System.Diagnostics;
[assembly: Dependency(typeof(PathManager_IOS))]
namespace yourproject.iOS
{
public class PathManager_IOS : IPathManager
{
[DllImport(ObjCRuntime.Constants.ObjectiveCLibrary, EntryPoint = "objc_msgSend")]
internal extern static IntPtr IntPtr_objc_msgSend(IntPtr receiver, IntPtr selector, UISemanticContentAttribute arg1);
public PathManager_IOS()
{
}
public void SetLayoutRTL()
{
try
{
Selector selector = new Selector("setSemanticContentAttribute:");
IntPtr_objc_msgSend(UIView.Appearance.Handle, selector.Handle, UISemanticContentAttribute.ForceRightToLeft);
}
catch (Exception s)
{
Debug.WriteLine("failed to set layout...."+s.Message.ToString());
}
}
public void SetLayoutLTR()
{
try
{
Selector selector = new Selector("setSemanticContentAttribute:");
IntPtr_objc_msgSend(UIView.Appearance.Handle, selector.Handle, UISemanticContentAttribute.ForceLeftToRight);
}
catch (Exception s)
{
Debug.WriteLine("failed to set layout...." + s.Message.ToString());
}
}
}
}
ps: please change "yourproject" to your project name...
To Call this on startup
in AppDelegate.cs
PathManager_IOS pathManager = new PathManager_IOS();
if (lang == 3)
{
pathManager.SetLayoutRTL();/* RTL */
}
if (lang == 1||lang == 2)
{
pathManager.SetLayoutLTR();/* LTR */
}
LoadApplication(new App(m, lang));
TO call this from the PCL shared pages or project
/* arabic */
DependencyService.Get<IPathManager>().SetLayoutRTL();
/* English */
DependencyService.Get<IPathManager>().SetLayoutLTR();
Don't forget to set the flow direction on language change
if(lang==3)
{//arabic
this.FlowDirection = FlowDirection.RightToLeft;
this.Master.FlowDirection= FlowDirection.RightToLeft;
this.Detail.FlowDirection= FlowDirection.RightToLeft;
}
hope this helps! all this for that hamburger icon !!!
Cheers,
Rabih
To force Android navigation Bar to be RTL use masterDetailPage renderer on Android project something like this:
public class MyMasterDetailPageRenderer : MasterDetailPageRenderer
{
public MyMasterDetailPageRenderer(Context context) : base(context)
{
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
toolbar.LayoutDirection = LayoutDirection.Rtl;
}
}
the first step is to set master direction flow
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="APPNAME.MainPage"
FlowDirection="RightToLeft">
and for Android you need to add android:supportsRtl="true" to AndroidManifest.xml like
<application android:label="APPNAME.Android" android:theme="#style/MainTheme" android:supportsRtl="true"></application>
and then your master page is rtl as well as the action bar.
I am using masterdetail page within this page i am using tabbed page now i want to show toolbar icon and search bar on the top of page.i am able to place toolbar icon but struggling with search bar.how to place it at the top its behavior should match with the search bar in whatsapp app and in youtube app
The WhatsApp search bar is just that, a SearchBar control which you can add to your XAML layout as follows:
<StackLayout>
<SearchBar Placeholder="Search" Text="{Binding Filter}" />
<ListView ItemSource="{Binding Items}">
...
</ListView>
</StackLayout>
Ensure you have a backing property for the filter. You can use the setter of this property to intercept people filtering the data and filter the Items property accordingly.
The YouTube search behaves a bit differently. The toolbar item pops a new screen modally where the search is handled similar to a UISearchController (on iOS). There is no Xamarin Forms drop-in control (that I'm aware of) that does this for you so you'll probably have to roll your own.
We can create a custom renderer on both Xamarin.iOS and Xamarin.Android to accomplish it.
Here's a sample application for reference:
https://github.com/brminnick/GitTrends
And here's a blog post that shows how to add a search bar to a Xamarin.Forms app for both Xamarin.iOS & Xamarin.Android: https://www.codetraveler.io/2019/08/10/adding-a-search-bar-to-xamarin-forms-navigationpage/
App.cs
Use a Xamarin.Forms Platform-Specific to use LargeTitles on the Xamarin.iOS app.
using Xamarin.Forms.PlatformConfiguration;
using Xamarin.Forms.PlatformConfiguration.iOSSpecific;
public class App : Xamarin.Forms.Application
{
public App()
{
var navigationPage = new Xamarin.Forms.NavigationPage(new MyContentPage());
navigationPage.On<iOS>().SetPrefersLargeTitles(true);
MainPage = navigationPage;
}
}
ISearchPage Interface
Create an Interface that can be used across the Xamarin.Forms, Xamarin.Android and Xamarin.iOS projects.
public interface ISearchPage
{
void OnSearchBarTextChanged(in string text);
event EventHandler<string> SearchBarTextChanged;
}
Xamarin.Forms Page
public class MyContentPage : ContentPage, ISearchPage
{
public MyContentPage()
{
SearchBarTextChanged += HandleSearchBarTextChanged
}
public event EventHandler<string> SearchBarTextChanged;
public void OnSearchBarTextChanged(in string text) => SearchBarTextChanged?.Invoke(this, text);
void HandleSearchBarTextChanged(object sender, string searchBarText)
{
//Logic to handle updated search bar text
}
}
iOS Custom Renderer
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UIKit;
using MyNamespace;
using MyNamespace.iOS;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(MyContentPage), typeof(SearchPageRenderer))]
namespace MyNamespace.iOS
{
public class SearchPageRenderer : PageRenderer, IUISearchResultsUpdating
{
readonly UISearchController _searchController;
public SearchPageRenderer()
{
_searchController = new UISearchController(searchResultsController: null)
{
SearchResultsUpdater = this,
DimsBackgroundDuringPresentation = false,
HidesNavigationBarDuringPresentation = false,
HidesBottomBarWhenPushed = true
};
_searchController.SearchBar.Placeholder = string.Empty;
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
if (ParentViewController.NavigationItem.SearchController is null)
{
ParentViewController.NavigationItem.SearchController = _searchController;
DefinesPresentationContext = true;
//Work-around to ensure the SearchController appears when the page first appears https://stackoverflow.com/a/46313164/5953643
ParentViewController.NavigationItem.SearchController.Active = true;
ParentViewController.NavigationItem.SearchController.Active = false;
}
}
public override void ViewWillDisappear(bool animated)
{
base.ViewWillDisappear(animated);
ParentViewController.NavigationItem.SearchController = null;
}
public void UpdateSearchResultsForSearchController(UISearchController searchController)
{
if (Element is ISearchPage searchPage)
searchPage.OnSearchBarTextChanged(searchController.SearchBar.Text);
}
}
}
Xamarin.Android Menu XML
In the Xamarin.Android project, in the Resources folder, create a new folder called menu (if one doesn't already exist).
Note: the folder, menu, has a lowercase 'm'
In the Resources > menu folder, create a new file called MainMenu.xml.
Open Resources > menu > MainMenu.xml
In MainMenu.xml add the following code:
<?xml version="1.0" encoding="utf-8" ?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/ActionSearch"
android:title="Filter"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>
Xamarin.Android CustomRenderer
Uses the Plugin.CurrentActivity NuGet Package.
using Android.Content;
using Android.Runtime;
using Android.Support.V7.Widget;
using Android.Text;
using Android.Views.InputMethods;
using Plugin.CurrentActivity;
using MyNamespace;
using MyNamespace.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(MyContentPage), typeof(SearchPageRenderer))]
namespace MyNamespace.Droid
{
public class SearchPageRenderer : PageRenderer
{
public SearchPageRenderer(Context context) : base(context)
{
}
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
if (Element is ISearchPage && Element is Page page && page.Parent is NavigationPage navigationPage)
{
//Workaround to re-add the SearchView when navigating back to an ISearchPage, because Xamarin.Forms automatically removes it
navigationPage.Popped += HandleNavigationPagePopped;
navigationPage.PoppedToRoot += HandleNavigationPagePopped;
}
}
//Adding the SearchBar in OnSizeChanged ensures the SearchBar is re-added after the device is rotated, because Xamarin.Forms automatically removes it
protected override void OnSizeChanged(int w, int h, int oldw, int oldh)
{
base.OnSizeChanged(w, h, oldw, oldh);
if (Element is ISearchPage && Element is Page page && page.Parent is NavigationPage navigationPage && navigationPage.CurrentPage is ISearchPage)
{
AddSearchToToolbar(page.Title);
}
}
protected override void Dispose(bool disposing)
{
if (GetToolbar() is Toolbar toolBar)
toolBar.Menu?.RemoveItem(Resource.Menu.MainMenu);
base.Dispose(disposing);
}
//Workaround to re-add the SearchView when navigating back to an ISearchPage, because Xamarin.Forms automatically removes it
void HandleNavigationPagePopped(object sender, NavigationEventArgs e)
{
if (sender is NavigationPage navigationPage
&& navigationPage.CurrentPage is ISearchPage)
{
AddSearchToToolbar(navigationPage.CurrentPage.Title);
}
}
void AddSearchToToolbar(string pageTitle)
{
if (GetToolbar() is Toolbar toolBar
&& toolBar.Menu?.FindItem(Resource.Id.ActionSearch)?.ActionView?.JavaCast<SearchView>().GetType() != typeof(SearchView))
{
toolBar.Title = pageTitle;
toolBar.InflateMenu(Resource.Menu.MainMenu);
if (toolBar.Menu?.FindItem(Resource.Id.ActionSearch)?.ActionView?.JavaCast<SearchView>() is SearchView searchView)
{
searchView.QueryTextChange += HandleQueryTextChange;
searchView.ImeOptions = (int)ImeAction.Search;
searchView.InputType = (int)InputTypes.TextVariationFilter;
searchView.MaxWidth = int.MaxValue; //Set to full width - http://stackoverflow.com/questions/31456102/searchview-doesnt-expand-full-width
}
}
}
void HandleQueryTextChange(object sender, SearchView.QueryTextChangeEventArgs e)
{
if (Element is ISearchPage searchPage)
searchPage.OnSearchBarTextChanged(e.NewText);
}
Toolbar GetToolbar() => CrossCurrentActivity.Current.Activity.FindViewById<Toolbar>(Resource.Id.toolbar);
}
}
Sample App
Here's a sample app for reference:
https://github.com/brminnick/GitTrends
And a blog post that shows how to add a search bar for both Xamarin.iOS and Xamarin.Android: https://www.codetraveler.io/2019/08/10/adding-a-search-bar-to-xamarin-forms-navigationpage/
Used User Control for Navbar. and hide Navigarionbar using
NavigationPage.SetHasNavigationBar (this, false);
Check following link may be it's help you. and i think it's for your requirement.
http://blog.xhackers.co/xamarin-forms-contentpage-with-searchbar-in-the-navigation-bar/
Placing a SearchBar in the top/navigation bar
How to include view in NavigationBar of Xamarin Forms?
install or update Android support repository, google play service and Google USB driver
if you'r using shell app you can use Shell.TitleView instead of Navigation.TitleView as the following :
<Shell.TitleView>
<SearchBar x:Name="search" Margin="10,10,10,10"
HorizontalOptions="FillAndExpand"/>
</Shell.TitleView>