Show ProgressBar programattically while user logging on - xamarin.android

I found this class at Centering ProgressBar Programmatically in Android which would display a progressbar programmatically, problem is it's an Xamarin Android Studio example and I'm trying to convert it to Xamarin for Visual Studio 2017. This is the code that I have successfully converted with those lines that I can't seem to find a Xamarin VS 2017 equivalent for.
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace OML_Android
{
class ProgressBarHandler
{
private ProgressBar mProgressBar;
private Context mContext;
public ProgressBarHandler(Context context)
{
mContext = context;
ViewGroup layout = (ViewGroup)((Activity)context).FindViewById(Android.Resource.Id.Content).RootView;
mProgressBar = new ProgressBar(context, null, Android.Resource.Attribute.ProgressBarStyleLarge);
// there is no setIndeterminate method for progressbar
mProgressBar.setIndeterminate(true);
// I cannot find an equivilent for LayoutParams
RelativeLayout.LayoutParams params = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MatchParent, RelativeLayout.LayoutParams.MatchParent);
RelativeLayout rl = new RelativeLayout(context);
// No equivalent for Gravity.CENTER
rl.SetGravity(Gravity.CENTER);
rl.AddView(mProgressBar);
layout.AddView(rl, params);
hide();
}
public void show()
{
mProgressBar.Visibility = Android.Views.ViewStates.Visible;
}
public void hide()
{
mProgressBar.Visibility = Android.Views.ViewStates.Invisible;
}
}
}
Once I have this converted and working I want it to overlay my logon view until the view finishes processing.

I help you transform Java code to C#, there is running GIF.
There is code.
class ProgressBarHandler
{
private ProgressBar mProgressBar;
private Context mContext;
public ProgressBarHandler(Context context)
{
mContext = context;
ViewGroup layout = (ViewGroup)((Activity)context).FindViewById(Android.Resource.Id.Content).RootView;
mProgressBar = new ProgressBar(context, null, Android.Resource.Attribute.ProgressBarStyleLarge);
// there is no setIndeterminate method for progressbar
// mProgressBar.SetIndeterminate(true);
mProgressBar.Indeterminate = true;
// I cannot find an equivilent for LayoutParams
RelativeLayout.LayoutParams layoutparams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MatchParent, RelativeLayout.LayoutParams.MatchParent);
RelativeLayout rl = new RelativeLayout(context);
// No equivalent for Gravity.CENTER
rl.SetGravity(GravityFlags.Center );
rl.AddView(mProgressBar);
layout.AddView(rl, layoutparams);
hide();
}
public void show()
{
mProgressBar.Visibility = Android.Views.ViewStates.Visible;
}
public void hide()
{
mProgressBar.Visibility = Android.Views.ViewStates.Invisible;
}
}
You can use it directly like following code in Activity.
var progress= new ProgressBarHandler(this);
progress.show();

Related

The attribute android:onClick="FabOnClick" crashes app when Floating Action Button clicked

There doesn't appear to be a lot of people using Xamarin for Visual Studio consequently there isn't a lot of information specific to that platform out there.
Having said that, I've been trying to get a Floating Action Button (FAB) to work and it's been quite the exercise. I finally got it to appear and assign it to a variable in the activity with help from the nice folks who use StackOverflow, but cannot get the android:onClick="FabOnClick" call to work. Clicking on the FAB causes the app to crash with the error:
Unhandled Exception:
Java.Lang.IllegalStateException: Could not find method FabOnClick(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.design.widget.FloatingActionButton with id 'fab' occurred
This is the code in my activity:
public void FabOnClick(View v)
{
int x = 1;
}
It doesn't really do anything because I'm just trying to capture the click event for now. I set a breakpoint on the int x = 1 line to see when it's is executed. So what am I missing?
* Update *
I updated my activity code based on #Digitalsa1nt's answer below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Acr.UserDialogs;
using Android.Net;
using System.Net;
using Android.Support.Design.Widget;
using System.Threading.Tasks;
using Android.Views.InputMethods;
using static Android.Views.View;
namespace OML_Android
{
[Activity(Label = "CreateAccount")]
public class CreateAccount : Activity
{
public string result = "";
public EditText aTextboxUsername;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.CreateAccount);
RequestedOrientation = Android.Content.PM.ScreenOrientation.Portrait;
aTextboxUsername = FindViewById<EditText>(Resource.Id.aTextboxUsername);
EditText aTextboxPassword = FindViewById<EditText>(Resource.Id.aTextboxPassword);
EditText aTextboxPassword2 = FindViewById<EditText>(Resource.Id.aTextboxPassword2);
EditText txtEmailAddress = FindViewById<EditText>(Resource.Id.txtEmailAddress);
EditText txtEmailAddress2 = FindViewById<EditText>(Resource.Id.txtEmailAddress2);
EditText txtFirstName = FindViewById<EditText>(Resource.Id.first_name);
EditText txtMI = FindViewById<EditText>(Resource.Id.mi);
EditText txtLastName = FindViewById<EditText>(Resource.Id.last_name);
EditText txtAddress = FindViewById<EditText>(Resource.Id.address);
EditText txtCity = FindViewById<EditText>(Resource.Id.city);
Spinner spnState = FindViewById<Spinner>(Resource.Id.state);
EditText txtZip = FindViewById<EditText>(Resource.Id.zip);
MaskedEditText.MaskedEditText txtPhone = FindViewById<MaskedEditText.MaskedEditText>(Resource.Id.phone);
Spinner spnCompany = FindViewById<Spinner>(Resource.Id.company_spinner);
Spinner spnDept = FindViewById<Spinner>(Resource.Id.department_spinner);
Spinner spnSection = FindViewById<Spinner>(Resource.Id.section_spinner);
Button ButtonSubmit = FindViewById<Button>(Resource.Id.button_submit);
ScrollView sv = FindViewById<ScrollView>(Resource.Id.scrollView1);
ButtonSubmit.SetBackgroundColor(Android.Graphics.Color.YellowGreen);
// Hide the keyboard (also doesn't work)
InputMethodManager board = (InputMethodManager)GetSystemService(Context.InputMethodService);
board.HideSoftInputFromWindow(aTextboxUsername.WindowToken, 0);
// get the floating action button.
FloatingActionButton myFab = FindViewById< FloatingActionButton>(Resource.Id.fab);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
DataInterfaceWeb.DataInterface myService = new DataInterfaceWeb.DataInterface();
myFab.Click += FabButton_Click(); // <-- get error here
try
{
ConnectivityManager connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);
NetworkInfo activeConnection = connectivityManager.ActiveNetworkInfo;
bool isOnline = (activeConnection != null) && activeConnection.IsConnected;
if (!isOnline)
{
showMessage("There is no internet or cell phone connection. Connect to a network or connect to a cellular network.", "ERROR");
}
}
catch (Exception ex)
{
showMessage("Connectivity Manager failed to create a connection due to error: " + ex.Message, "ERROR");
};
// Create your application here
ButtonSubmit.Click += async (sender, e) =>
{
try
{
result = myService.CheckForUser(Master.username, Master.password, aTextboxUsername.Text);
if (result.ToUpper() == "Y")
{
await showMessage("Username " + aTextboxUsername.Text + " is already in use. Please choose another", "ERROR");
// aTextboxUsername.SetSelectAllOnFocus(true);
aTextboxUsername.RequestFocus();
View insideView = FindViewById<EditText>(Resource.Id.aTextboxUsername);
sv.ScrollTo(0, (int)insideView.GetY());
aTextboxUsername.SelectAll();
}
}
catch (Exception ex)
{
showMessage("Account creation attempt failed due to error: " + ex.Message, "ERROR");
}
};
}
public async Task showMessage(string message, string messageType)
{
var result = await UserDialogs.Instance.ConfirmAsync(new ConfirmConfig
{
Message = messageType + System.Environment.NewLine + message,
OkText = "Ok",
});
}
public void FabButton_Click()
{
int x = 1;
}
}
}
The error I get now is:
Cannot implicitly convert 'void' to 'SystemEventHandler' on the line myFab.Click += FabButton_Click();.
#Digitalsa1nt did point me in the right direction. Instead of
fabButton.Click += FabButton_Click;
I just wired up an event, as the error suggested (duh):
myFab.Click += (sender, e) =>
{
FabButton_Click();
};
It now works as I would expect.
So I'm making a couple of assumptions in this answer. Firstly that you are working with a Xamarin.Native project and not a Xamarin.Forms project.
Secondly I am assuming you are using the FloatingActionButton from one of the support libraries such as: Android.Support.Design.Widget (base / V4 / V7).
Once you've defined your FAB within the AXML Layout page:
<android.support.design.widget.FloatingActionButton
app:backgroundTint="#color/colourPrimary"
android:id="#+id/fabButton"
android:src="#drawable/image"
app:fabSize="normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:elevation="16dp"
android:translationZ="12dp"
app:rippleColor="#ffa9a9a9" />
You can get it from within your activity as such:
using Android.Support.Design.Widget;
// declare variable
private FloatingActionButton fabButton;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// call base
base.OnCreateView(inflater, container, savedInstanceState);
// inflate our view
var view = inflater.Inflate(Resource.Layout.MainTabWishlistPage, container, false);
// get our instance of the button using the resource ID.
fabButton = view.FindViewById<FloatingActionButton>(Resource.Id.fabButton);
// assign to click event
fabButton.Click += FabButton_Click;
}
private void FabButton_Click(object sender, EventArgs e)
{
int x = 1;
}
The above example is based on it being a fragment rather than an activity, but the methodology is the same.
Official Git Repo:
Xamarin/monodroid-samples - Floating Action Button Basic
Random online guide:
android-material-design-floating-action
In case this is a Xamarin.Forms project, look into James Montemagno's library (p.s one of the developers that works on Xamarin and creates tons of libraries to help make your life easier, definitely look through his other repos.)
jamesmontemagno/FloatingActionButton-for-Xamarin.Android

.DismissModalViewController closes all my pages. Why?

I am using an image picker in my xamarin forms in order to pick an image from gallery to my program...
But, only in IOS device, when I close the image picker using
imagePicker.DismissModalViewController(true);
all my pop ups that is opened are closed with the imagePicker...
Does someone know why? or how I can solve that?
I am using DependencyService to do that in both
This is the code in IOS project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Foundation;
using UIKit;
using neoFly_Montana.iOS;
using Xamarin.Forms;
using neoFly_Montana.Interface;
using System.Threading.Tasks;
using System.IO;
[assembly: Dependency(typeof(PicturePickerImplementation))]
namespace neoFly_Montana.iOS
{
public class PicturePickerImplementation : IPicturePicker
{
TaskCompletionSource<Stream> taskCompletionSource;
UIImagePickerController imagePicker;
public Task<Stream> GetImageStreamAsync()
{
// Create and define UIImagePickerController
imagePicker = new UIImagePickerController
{
SourceType = UIImagePickerControllerSourceType.PhotoLibrary,
MediaTypes = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.PhotoLibrary)
};
// Set event handlers
imagePicker.FinishedPickingMedia += OnImagePickerFinishedPickingMedia;
imagePicker.Canceled += OnImagePickerCancelled;
// Present UIImagePickerController;
UIWindow window = UIApplication.SharedApplication.KeyWindow;
var viewController = window.RootViewController;
viewController.PresentModalViewController(imagePicker, true);
// Return Task object
taskCompletionSource = new TaskCompletionSource<Stream>();
return taskCompletionSource.Task;
}
void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs args)
{
UIImage image = args.EditedImage ?? args.OriginalImage;
if (image != null)
{
// Convert UIImage to .NET Stream object
NSData data = image.AsJPEG(1);
Stream stream = data.AsStream();
// Set the Stream as the completion of the Task
taskCompletionSource.SetResult(stream);
}
else
{
taskCompletionSource.SetResult(null);
}
imagePicker.DismissModalViewController(true);
}
void OnImagePickerCancelled(object sender, EventArgs args)
{
taskCompletionSource.SetResult(null);
imagePicker.DismissModalViewController(true);
}
}
}
I am using RG.PLUGIN.POPUP

Xamarin Android TypefaceSpan with custom font in Assets folder

As the title states, I need to use a TypefaceSpan object with a custom font present inside the Assets but I can't find the correct way to achieve this.
The file of the font is "HelveticaNeueLTCom-BdCn.ttf"
These are my two attempt which did not work for me:
// first attempt
var textViewTitle = new TextView(Context);
var span = new SpannableString("MyLongTitle");
span.SetSpan(new TypefaceSpan("HelveticaNeueLTCom-BdCn.ttf"), 0, 5, SpanTypes.ExclusiveExclusive);
textViewTitle.TextFormatted = span;
// second attempt
var textViewTitle = new TextView(Context);
var span = new SpannableString("MyLongTitle");
span.SetSpan(new Typeface(Typeface.CreateFromAsset(Context.Assets, "fonts/HelveticaNeueLTCom-BdCn.ttf")), 0, 5, SpanTypes.ExclusiveExclusive);
textViewTitle.TextFormatted = span;
Anyone has some hints or advice?
Almost one year later but I faced the same problem and I found this way of achieving it.
I saw you posted the same question in the Xamarin forum here but the link you wrote in your answer is broken. However, I think that it is this post that helped you as it helped me.
So here the way to go.
First create a custom TypefaceSpan like this
using System;
using Android.OS;
using Android.Runtime;
using Android.Text.Style;
using Android.Graphics;
using Android.Text;
namespace Droid.Spans
{
public class CustomTypefaceSpan : TypefaceSpan
{
private readonly Typeface _typeface;
public CustomTypefaceSpan(Typeface typeface)
: base(string.Empty)
{
_typeface = typeface;
}
public CustomTypefaceSpan(IntPtr javaReference, JniHandleOwnership transfer)
: base(javaReference, transfer)
{
}
public CustomTypefaceSpan(Parcel src)
: base(src)
{
}
public CustomTypefaceSpan(string family)
: base(family)
{
}
public override void UpdateDrawState(TextPaint ds)
{
ApplyTypeface(ds, _typeface);
}
public override void UpdateMeasureState(TextPaint paint)
{
ApplyTypeface(paint, _typeface);
}
private static void ApplyTypeface(Paint paint, Typeface tf)
{
paint.SetTypeface(tf);
}
}
}
Then use this CustomTypefaceSpan to add a span to the SpannableString
var spannableString = new SpannableString("Anything to write with a special font");
spannableString.SetSpan(new CustomTypefaceSpan(Typeface.CreateFromAsset(Assets, "HelveticaNeueLTCom-BdCn.ttf"), 0, 7, SpanTypes.InclusiveInclusive);
textView.TextFormatted = spannableString;

How to fix rotation for WebView custom renderer for iOS using Xamarin.Forms?

I have created a custom renderer for a WebView in my Xamarin.Forms project. The WebView works great on Android. Unfortunately, on iOS, when the device is rotated, the webpage (any webpage) does not correctly adjust to the new dimensions of the WebView. If I use the built in WebView for Forms, the pages correctly resize on rotate.
What am I doing wrong with my custom renderer?
Below is a stripped down version of my custom renderer (the issue still occurs):
using Xamarin.Forms.Platform.iOS;
using Xamarin.Forms;
using UIKit;
using Foundation;
[assembly: ExportRenderer(typeof(WebView), typeof(MyProject.iOS.WebViewRenderer))]
namespace MyProject.iOS {
public class WebViewRenderer : ViewRenderer<WebView, UIWebView> {
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e) {
if (Control == null) {
var webView = new UIWebView(Frame);
webView.AutoresizingMask = UIViewAutoresizing.All;
SetNativeControl(webView);
webView.LoadRequest(new NSUrlRequest(new NSUrl("http://cnn.com")));
}
}
}
}
To fix the issue, add the following to the custom renderer:
public override SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint) {
return new SizeRequest(Size.Zero, Size.Zero);
}
To fix the rotate problem you need to use the NativeView.Bounds when you create the UIWebView.
[assembly: ExportRenderer(typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespaceMobile.App.iOS
{
public class CustomWebViewRenderer : ViewRenderer<CustomWebView, UIWebView>
{
protected override void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
var webView = new UIWebView(NativeView.Bounds);
webView.ShouldStartLoad += HandleShouldStartLoad;
webView.AutoresizingMask = UIViewAutoresizing.All;
webView.ScalesPageToFit = true;
SetNativeControl(webView);
webView.LoadRequest(new NSUrlRequest(new NSUrl(Element.Url)));
}
}
public override SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint)
{
return new SizeRequest(Size.Zero, Size.Zero);
}
}
}

Can't create Xamarin Forms Picker custom rendere

Hi i easily created custom renderer for Forms Entry control, but when i tried to create one to Picker i get this error:
Error CS0115: `Punteam.iOS.PunteamPickerRederer.OnElementChanged(Xamarin.Forms.Platform.iOS.ElementChangedEventArgs<Xamarin.Forms.Picker>)' is marked as an override but no suitable method found to override (CS0115) (Punteam.iOS)
this is my code on Forms project:
using System;
using Xamarin.Forms;
namespace Punteam
{
public class PunteamPicker : Picker
{
}
}
on IOS Project:
using Xamarin.Forms.Platform.iOS;
using Xamarin.Forms;
using Xamarin.Forms.Platform;
using Punteam;
using Punteam.iOS;
using UIKit;
using EventKitUI;
[assembly: ExportRenderer (typeof(PunteamPicker), typeof(PunteamPickerRederer))]
namespace Punteam.iOS
{
public class PunteamPickerRederer : PunteamPicker
{
protected override void OnElementChanged (ElementChangedEventArgs<Picker> e)
{
/* base.OnElementChanged (e);
this.Control.TextAlignment = MonoTouch.UIKit.UITextAlignment.Center;
this.Control.TextColor = UIColor.White;
this.Control.BackgroundColor = UIColor.Clear;
this.Control.BorderStyle = UITextBorderStyle.RoundedRect;
this.Layer.BorderWidth = 1.0f;
this.Layer.CornerRadius = 4.0f;
this.Layer.MasksToBounds = true;
this.Layer.BorderColor = UIColor.White.CGColor;*/
}
}
}
Any body know's Why i get this error?
public class PunteamPickerRederer : PunteamPicker
should be
public class PunteamPickerRederer : PickerRenderer

Resources