Adding left and right full swipe gesture on listview using xamarin forms - xamarin

Currently i have a listview which stores the medications of my users, i want to implement a swipe gesture so that the user can simply swipe left or right to tell if the medication has been taken or not taken.
Is there a way to add a left and right full swipe gesture in a listview just like the way that apple has implemented in their mail.

Note:it cannot achieved moved item follow with fingertip, but could achieved left and right gestures
First, you should build swipe compoment using gesture
SwipeGestureGrid.cs
public class SwipeGestureGrid : Grid
{
#region Private Member
private double _gestureX { get; set; }
private double _gestureY { get; set; }
private bool IsSwipe { get; set; }
#endregion
#region Public Member
#region Events
#region Tapped
public event EventHandler Tapped;
protected void OnTapped(EventArgs e)
{
if (Tapped != null)
Tapped(this, e);
}
#endregion
#region SwipeUP
public event EventHandler SwipeUP;
protected void OnSwipeUP(EventArgs e)
{
if (SwipeUP != null)
SwipeUP(this, e);
}
#endregion
#region SwipeDown
public event EventHandler SwipeDown;
protected void OnSwipeDown(EventArgs e)
{
if (SwipeDown != null)
SwipeDown(this, e);
}
#endregion
#region SwipeRight
public event EventHandler SwipeRight;
protected void OnSwipeRight(EventArgs e)
{
if (SwipeRight != null)
SwipeRight(this, e);
}
#endregion
#region SwipeLeft
public event EventHandler SwipeLeft;
protected void OnSwipeLeft(EventArgs e)
{
if (SwipeLeft != null)
SwipeLeft(this, e);
}
#endregion
#endregion
public double Height
{
get
{
return HeightRequest;
}
set
{
HeightRequest = value;
}
}
public double Width
{
get
{
return WidthRequest;
}
set
{
WidthRequest = value;
}
}
#endregion
public SwipeGestureGrid()
{
PanGestureRecognizer panGesture = new PanGestureRecognizer();
panGesture.PanUpdated += PanGesture_PanUpdated;
TapGestureRecognizer tapGesture = new TapGestureRecognizer();
tapGesture.Tapped += TapGesture_Tapped;
GestureRecognizers.Add(panGesture);
GestureRecognizers.Add(tapGesture);
}
private void TapGesture_Tapped(object sender, EventArgs e)
{
try
{
if (!IsSwipe)
OnTapped(null);
IsSwipe = false;
}
catch (Exception ex)
{
}
}
private void PanGesture_PanUpdated(object sender, PanUpdatedEventArgs e)
{
try
{
switch (e.StatusType)
{
case GestureStatus.Running:
{
_gestureX = e.TotalX;
_gestureY = e.TotalY;
}
break;
case GestureStatus.Completed:
{
IsSwipe = true;
//Debug.WriteLine("{0} {1}", _gestureX, _gestureY);
if (Math.Abs(_gestureX) > Math.Abs(_gestureY))
{
if (_gestureX > 0)
{
OnSwipeRight(null);
}
else
{
OnSwipeLeft(null);
}
}
else
{
if (_gestureY > 0)
{
OnSwipeDown(null);
}
else
{
OnSwipeUP(null);
}
}
}
break;
}
}
catch (Exception ex)
{
}
}
}
Next using datatemplate in listview andattach event for GesturecompomentPage.cs
ListView lsvData = new ListView()
{
VerticalOptions = LayoutOptions.Fill,
HorizontalOptions = LayoutOptions.Fill,
BackgroundColor = Color.White,
HasUnevenRows = true,
};
List<string> lstData = new List<string>();
public Pages()
{
#region DataTemplate
DataTemplate ListDataTemplate = new DataTemplate(() =>
{
#region DataArea of Template
SwipeGestureGrid gridData = new SwipeGestureGrid()
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
HeightRequest = 60,
RowDefinitions =
{
new RowDefinition { },
},
ColumnDefinitions =
{
new ColumnDefinition { },
}
};
#endregion
#region Base of Template
Grid gridBase = new Grid()
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
HeightRequest = 60,
RowDefinitions =
{
new RowDefinition { },
},
ColumnDefinitions =
{
new ColumnDefinition { },
//Put Cells Data here
new ColumnDefinition { Width = new GridLength(0,
GridUnitType.Absolute)}, //Button for Cells here
},
};
#endregion
Label lblText = new Label
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
FontAttributes = FontAttributes.Bold,
VerticalTextAlignment = TextAlignment.End,
TextColor = Color.Black,
BackgroundColor = Color.Silver,
LineBreakMode = LineBreakMode.TailTruncation,
FontSize = 18,
};
lblText.SetBinding(Label.TextProperty, ".");
ImageButton btnCellDelete = new ImageButton() { Source = "Delete" };
gridData.Children.Add(lblText, 0, 0);
gridBase.Children.Add(gridData, 0, 0);
gridBase.Children.Add(btnCellDelete, 1, 0);
gridData.SwipeLeft += GridTemplate_SwipeLeft;
gridData.SwipeRight += GridTemplate_SwipeRight; ;
gridData.Tapped += GridTemplate_Tapped; ;
btnCellDelete.Clicked += BtnCellDelete_Clicked; ;
return new ViewCell
{
View = gridBase,
Height = 60,
};
});
#endregion
for (int i = 1; i <= 100; i++)
{
lstData.Add(i.ToString());
}
lsvData.ItemTemplate = ListDataTemplate;
lsvData.ItemsSource = lstData;
Content = lsvData;
}
Add the event.SwipeLeft to show DeleteButton
private void GridTemplate_SwipeLeft(object sender, EventArgs e)
{
try
{
if (sender is SwipeGestureGrid)
{
var templateGrid = ((SwipeGestureGrid)sender).Parent;
if (templateGrid != null && templateGrid is Grid)
{
var CellTemplateGrid = (Grid)templateGrid;
CellTemplateGrid.ColumnDefinitions[1].Width = new GridLength(60, GridUnitType.Absolute);
}
}
}
catch (Exception ex)
{
}
}
swiperight to hide delete button
private void GridTemplate_SwipeRight(object sender, EventArgs e)
{
try
{
if (sender is SwipeGestureGrid)
{
var templateGrid = ((SwipeGestureGrid)sender).Parent;
if (templateGrid != null && templateGrid is Grid)
{
var CellTemplateGrid = (Grid)templateGrid;
CellTemplateGrid.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Absolute);
}
}
}
catch (Exception ex)
{
}
}
Delete button click event
private void BtnCellDelete_Clicked(object sender, EventArgs e)
{
try
{
if (sender is ImageButton)
{
var templateGrid = ((ImageButton)sender);
//templateGrid.Parent = gridBase
//templateGrid.Parent.Parent = cell
if (templateGrid.Parent != null && templateGrid.Parent.Parent != null && templateGrid.Parent.Parent.BindingContext != null && templateGrid.Parent.Parent.BindingContext is string)
{
var deletedate = templateGrid.Parent.Parent.BindingContext as string;
lstData.RemoveAll(f => f == deletedate);
lsvData.ItemsSource = null;
lsvData.ItemsSource = lstData;
}
}
}
catch (Exception ex)
{
}
}
There is all code.
https://github.com/act70255/ListViewSwipeGesture

I will create a listview with a custom cells
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/listview/customizing-cell-appearance
and i add swipe left and right gestures on a grid inside to a ViewCell
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/gestures/swipe
on left swipe i expand with animation something like a grid column where on start the width is 0 and after swap animated to some width. Same with right swipe.
Check for the animation the OnExpandExchange() method from here
https://github.com/xamarinium/FlippingAndResizableUI/blob/master/FlippingAndResizableView/BitcoinView.xaml.cs

Related

How to make focus event / effect for every IOS element?

I have made the following focus effect for Xamarin.Forms.Android so when the keyboard is focused on the element it shows blue rectangle around it.:
protected override void OnAttached()
{
try
{
OriginalBackground = Container.Background;
if(Control != null)
{
Control.FocusChange += Control_FocusChange;
}
else
{
Container.FocusChange += Control_FocusChange;
}
}
catch (Exception ex)
{
Console.WriteLine("Cannot set property on attached control. Error: ", ex.Message);
}
}
protected override void OnDetached()
{
}
protected override void OnElementPropertyChanged(System.ComponentModel.PropertyChangedEventArgs args)
{
base.OnElementPropertyChanged(args);
}
private void Control_FocusChange(object sender, FocusChangeEventArgs e)
{
if(Control != null)
{
if (Control.HasFocus)
{
Control.SetBackgroundColor(Android.Graphics.Color.Transparent);
Control.SetBackgroundResource(Resource.Drawable.focusFrame);
}
else
{
Control.SetBackground(OriginalBackground);
}
}
else
{
if (Container.HasFocus)
{
Container.SetBackgroundColor(Android.Graphics.Color.Red);
Container.SetBackgroundResource(Resource.Drawable.focusFrame);
}
else
{
Container.SetBackground(OriginalBackground);
}
}
}
Can someone tell me how to the same effect for Xamarin.Forms.IOS ? I tried the following code but it doesn't work on focusing the app the same way as Android. Somehow there isn't an event or perhaps I am missing it for IOS:
UIColor backgroundColor;
UIView view;
public Func<Brush, CALayer> OriginalBackground { get; private set; }
protected override void OnAttached()
{
try
{
OriginalBackground = Container.GetBackgroundLayer;
if (Container != null)
{
this.Container.DidUpdateFocus()
CreateRectange();
}
}
catch (Exception ex)
{
Console.WriteLine("Cannot set property on attached control. Error: ", ex.Message);
}
}
private void CreateRectange()
{
view = new UIView();
view.BackgroundColor = UIColor.Clear;
view.Frame = new CGRect(30, 100, 36, 36);
var maskLayer = new CAShapeLayer();
UIBezierPath bezierPath = UIBezierPath.FromRoundedRect(view.Bounds, (UIRectCorner.TopLeft | UIRectCorner.BottomLeft), new CGSize(18.0, 18.0));
maskLayer.Path = bezierPath.CGPath;
maskLayer.Frame = view.Bounds;
maskLayer.StrokeColor = UIColor.Black.CGColor; //set the borderColor
maskLayer.FillColor = UIColor.Red.CGColor; //set the background color
maskLayer.LineWidth = 1; //set the border width
view.Layer.AddSublayer(maskLayer);
Container.AddSubview(view);
}
protected override void OnDetached()
{
}
protected override void OnElementPropertyChanged(PropertyChangedEventArgs args)
{
base.OnElementPropertyChanged(args);
try
{
if (args.PropertyName == "IsFocused")
{
Control.AddSubview(view);
}
}
catch (Exception ex)
{
Console.WriteLine("Cannot set property on attached control. Error: ", ex.Message);
}
}
At first, the frame's size should fit the control. And then you need to set the maskLayer.FillColor as UIColor.Clear.CGColor to make the control's content will show correctly.
You can try the following code:
UIView view;
float width,height;
public Func<Brush, CALayer> OriginalBackground { get; private set; }
protected override void OnAttached()
{
}
private void CreateRectange()
{
height = (float)Control.Frame.Height;
width = (float)Control.Frame.Width;
view = new UIView();
view.BackgroundColor = UIColor.Clear;
view.Frame = new CGRect(0,0,width,height);
var maskLayer = new CAShapeLayer();
UIBezierPath bezierPath = UIBezierPath.FromRoundedRect(view.Bounds, (UIRectCorner.TopLeft | UIRectCorner.BottomLeft), new CGSize(0,0));
maskLayer.Path = bezierPath.CGPath;
maskLayer.Frame = view.Bounds;
maskLayer.StrokeColor = UIColor.Red.CGColor; //set the borderColor
maskLayer.FillColor = UIColor.Clear.CGColor; //set the background color
maskLayer.LineWidth = 1; //set the border width
view.Layer.AddSublayer(maskLayer);
}
protected override void OnDetached()
{
}
protected override void OnElementPropertyChanged(PropertyChangedEventArgs args)
{
base.OnElementPropertyChanged(args);
try
{
if (args.PropertyName == "IsFocused")
{
CreateRectange();
Control.AddSubview(view);
}
}
catch (Exception ex)
{
Console.WriteLine("Cannot set property on attached control. Error: ", ex.Message);
}
}

Xmarin.forms iOS check whether captured photo contains face or not

In my xamarin.forms app, I created a custom camera by using Camera view and custom renders. Everything works fine. In android after the photo capture I can check whether the taken photo contains a face or not.It is done by using Camera.IFaceDetectionListener. My question is how can I achieve this in iOS? I know there is vision API. But I don't want the live face tracking. I just simply want to check whether the taken photo contains face. Any help is appreciated.
My iOS CameraPreview
public class UICameraPreview : UIView, IAVCaptureMetadataOutputObjectsDelegate
{
AVCaptureVideoPreviewLayer previewLayer;
public AVCaptureDevice[] videoDevices;
CameraOptions cameraOptions;
public AVCaptureStillImageOutput stillImageOutput;
public AVCaptureDeviceInput captureDeviceInput;
public AVCaptureDevice device;
public event EventHandler<EventArgs> Tapped;
public AVCaptureSession CaptureSession { get; set; }
public bool IsPreviewing { get; set; }
public AVCaptureStillImageOutput CaptureOutput { get; set; }
public UICameraPreview(CameraOptions options)
{
cameraOptions = options;
IsPreviewing = false;
Initialize();
}
public override void LayoutSubviews()
{
base.LayoutSubviews();
if (previewLayer != null)
previewLayer.Frame = Bounds;
}
public override void TouchesBegan(NSSet touches, UIEvent evt)
{
base.TouchesBegan(touches, evt);
OnTapped();
}
protected virtual void OnTapped()
{
var eventHandler = Tapped;
if (eventHandler != null)
{
eventHandler(this, new EventArgs());
}
}
void Initialize()
{
CaptureSession = new AVCaptureSession();
previewLayer = new AVCaptureVideoPreviewLayer(CaptureSession)
{
Frame = Bounds,
VideoGravity = AVLayerVideoGravity.ResizeAspectFill
};
videoDevices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);
var cameraPosition = (cameraOptions == CameraOptions.Front) ? AVCaptureDevicePosition.Front : AVCaptureDevicePosition.Back;
device = videoDevices.FirstOrDefault(d => d.Position == cameraPosition);
if (device == null)
{
return;
}
NSError error;
captureDeviceInput = new AVCaptureDeviceInput(device, out error);
CaptureSession.AddInput(captureDeviceInput);
var dictionary = new NSMutableDictionary();
dictionary[AVVideo.CodecKey] = new NSNumber((int)AVVideoCodec.JPEG);
stillImageOutput = new AVCaptureStillImageOutput()
{
OutputSettings = new NSDictionary()
};
CaptureSession.AddOutput(stillImageOutput);
Layer.AddSublayer(previewLayer);
CaptureSession.StartRunning();
IsPreviewing = true;
}
// Photo Capturing
public async Task CapturePhoto()
{
try
{
var videoConnection = stillImageOutput.ConnectionFromMediaType(AVMediaType.Video);
var sampleBuffer = await stillImageOutput.CaptureStillImageTaskAsync(videoConnection);
var jpegData = AVCaptureStillImageOutput.JpegStillToNSData(sampleBuffer);
var photo = new UIImage(jpegData);
var rotatedPhoto = RotateImage(photo, 180f);
var img = rotatedPhoto;
CALayer layer = new CALayer
{
ContentsScale = 1.0f,
Frame = Bounds,
Contents = rotatedPhoto.CGImage //Contents = photo.CGImage,
};
CaptureSession.StopRunning();
photo.SaveToPhotosAlbum((image, error) =>
{
if (!string.IsNullOrEmpty(error?.LocalizedDescription))
{
Console.Error.WriteLine($"\t\t\tError: {error.LocalizedDescription}");
}
});
}
catch (Exception ex)
{
}
//MainPage.UpdateSource(UIImageFromLayer(layer).AsJPEG().AsStream());
//MainPage.UpdateImage(UIImageFromLayer(layer).AsJPEG().AsStream());
}
}
My CameraPreviewRenderer
public class CameraPreviewRenderer : ViewRenderer<CameraPreview, UICameraPreview>, IAVCaptureMetadataOutputObjectsDelegate
{
UICameraPreview uiCameraPreview;
AVCaptureSession captureSession;
AVCaptureDeviceInput captureDeviceInput;
AVCaptureStillImageOutput stillImageOutput;
protected override void OnElementChanged(ElementChangedEventArgs<CameraPreview> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
// Unsubscribe
uiCameraPreview.Tapped -= OnCameraPreviewTapped;
}
if (e.NewElement != null)
{
if (Control == null)
{
uiCameraPreview = new UICameraPreview(e.NewElement.Camera);
SetNativeControl(uiCameraPreview);
MessagingCenter.Subscribe<Camera_Popup>(this, "CaptureClick", async (sender) =>
{
try
{
// Using messeging center to take photo when clicking button from shared code
var data = new AVCaptureMetadataOutputObjectsDelegate();
await uiCameraPreview.CapturePhoto();
}
catch (Exception ex)
{
return;
}
});
}
MessagingCenter.Subscribe<Camera_Popup>(this, "RetryClick", (sender) =>
{
Device.BeginInvokeOnMainThread(() =>
{
uiCameraPreview.CaptureSession.StartRunning();
uiCameraPreview.IsPreviewing = true;
});
});
MessagingCenter.Subscribe<Camera_Popup>(this, "FlipClick", (sender) =>
{
try
{
var devicePosition = uiCameraPreview.captureDeviceInput.Device.Position;
if (devicePosition == AVCaptureDevicePosition.Front)
{
devicePosition = AVCaptureDevicePosition.Back;
}
else
{
devicePosition = AVCaptureDevicePosition.Front;
}
uiCameraPreview.device = uiCameraPreview.videoDevices.FirstOrDefault(d => d.Position == devicePosition);
uiCameraPreview.CaptureSession.BeginConfiguration();
uiCameraPreview.CaptureSession.RemoveInput(uiCameraPreview.captureDeviceInput);
uiCameraPreview.captureDeviceInput = AVCaptureDeviceInput.FromDevice(uiCameraPreview.device);
uiCameraPreview.CaptureSession.AddInput(uiCameraPreview.captureDeviceInput);
uiCameraPreview.CaptureSession.CommitConfiguration();
}
catch (Exception ex)
{
var abc = ex.InnerException.Message;
}
});
uiCameraPreview.Tapped += OnCameraPreviewTapped;
}
}
void OnCameraPreviewTapped(object sender, EventArgs e)
{
if (uiCameraPreview.IsPreviewing)
{
uiCameraPreview.CaptureSession.StopRunning();
uiCameraPreview.IsPreviewing = false;
}
else
{
uiCameraPreview.CaptureSession.StartRunning();
uiCameraPreview.IsPreviewing = true;
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Control.CaptureSession.Dispose();
Control.Dispose();
}
base.Dispose(disposing);
}
}
The CoreImage framework has CIDetector that provides image detectors for faces, QR codes, text, .... in which you pass in an image and you get a specific "feature set" back.
Example from Xamarin docs:
var imageFile = "photoFace2.jpg";
var image = new UIImage(imageFile);
var context = new CIContext ();
var detector = CIDetector.CreateFaceDetector (context, true);
var ciImage = CIImage.FromCGImage (image.CGImage);
var features = detector.GetFeatures (ciImage);
Console.WriteLine ("Found " + features.Length + " faces");
re: https://learn.microsoft.com/en-us/dotnet/api/CoreImage.CIDetector?view=xamarin-ios-sdk-12

Custom Renderer for Picker in Xamarin.Forms

I want to customize my picker. I created a custom renderer for my picker but I dont know how the customization settings. How can I change the font style and size of the item? and How can I remove the two lines?
public class CustomPickerRenderer : PickerRenderer
{
public CustomPickerRenderer(Context context) : base(context)
{
AutoPackage = false;
}
protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
base.OnElementChanged(e);
if (e.OldElement == null)
{
Control.Background = null;
var layoutParams = new MarginLayoutParams(Control.LayoutParameters);
layoutParams.SetMargins(0, 0, 0, 0);
Control.LayoutParameters = layoutParams;
Control.SetPadding(0, 0, 0, 0);
SetPadding(0, 0, 0, 0);
}
}
}
If you want to set the fontSize of the text , you first need to customize a subclass extends from NumberPicker and overwrite the method AddView.
public class TextColorNumberPicker: NumberPicker
{
public TextColorNumberPicker(Context context) : base(context)
{
}
public override void AddView(View child, int index, ViewGroup.LayoutParams #params)
{
base.AddView(child, index, #params);
UpdateView(child);
}
public void UpdateView(View view)
{
if ( view is EditText ) {
//set the font of text
((EditText)view).TextSize = 8;
}
}
}
If you want to remove the lines,you should rewrite the NumberPicker
in Android Custom Renderer
public class MyAndroidPicker:PickerRenderer
{
IElementController ElementController => Element as IElementController;
public MyAndroidPicker()
{
}
private AlertDialog _dialog;
protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
base.OnElementChanged(e);
if (e.NewElement == null || e.OldElement != null)
return;
Control.Click += Control_Click;
}
protected override void Dispose(bool disposing)
{
Control.Click -= Control_Click;
base.Dispose(disposing);
}
private void SetPickerDividerColor(TextColorNumberPicker picker)
{
Field[] fields = picker.Class.GetDeclaredFields();
foreach (Field pf in fields)
{
if(pf.Name.Equals("mSelectionDivider"))
{
pf.Accessible = true;
// set the color as transparent
pf.Set(picker, new ColorDrawable(this.Resources.GetColor(Android.Resource.Color.Transparent)));
}
}
}
private void Control_Click(object sender, EventArgs e)
{
Picker model = Element;
var picker = new TextColorNumberPicker(Context);
if (model.Items != null && model.Items.Any())
{
picker.MaxValue = model.Items.Count - 1;
picker.MinValue = 0;
picker.SetBackgroundColor(Android.Graphics.Color.Yellow);
picker.SetDisplayedValues(model.Items.ToArray());
//call the method after you setting DisplayedValues
SetPickerDividerColor(picker);
picker.WrapSelectorWheel = false;
picker.Value = model.SelectedIndex;
}
var layout = new LinearLayout(Context) { Orientation = Orientation.Vertical };
layout.AddView(picker);
ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, true);
var builder = new AlertDialog.Builder(Context);
builder.SetView(layout);
builder.SetTitle(model.Title ?? "");
builder.SetNegativeButton("Cancel ", (s, a) =>
{
ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
// It is possible for the Content of the Page to be changed when Focus is changed.
// In this case, we'll lose our Control.
Control?.ClearFocus();
_dialog = null;
});
builder.SetPositiveButton("Ok ", (s, a) =>
{
ElementController.SetValueFromRenderer(Picker.SelectedIndexProperty, picker.Value);
// It is possible for the Content of the Page to be changed on SelectedIndexChanged.
// In this case, the Element & Control will no longer exist.
if (Element != null)
{
if (model.Items.Count > 0 && Element.SelectedIndex >= 0)
Control.Text = model.Items[Element.SelectedIndex];
ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
// It is also possible for the Content of the Page to be changed when Focus is changed.
// In this case, we'll lose our Control.
Control?.ClearFocus();
}
_dialog = null;
});
_dialog = builder.Create();
_dialog.DismissEvent += (ssender, args) =>
{
ElementController?.SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
};
_dialog.Show();
}
}
I also used this CustomRenderer which was posted before only instead of overriding it you can change the properties like this.
private void Control_Click(object sender, EventArgs e)
{
Picker model = Element;
var picker = new MyNumberPicker(Context);
if (model.Items != null && model.Items.Any())
{
// set style here
picker.MaxValue = model.Items.Count - 1;
picker.MinValue = 0;
picker.SetBackgroundColor(Android.Graphics.Color.Transparent);
picker.SetDisplayedValues(model.Items.ToArray());
//call the method after you setting DisplayedValues
SetPickerDividerColor(picker);
picker.WrapSelectorWheel = false;
picker.Value = model.SelectedIndex;
// change Text Size and Divider
picker.TextSize = 30;
picker.SelectionDividerHeight = 1;
}

How to set Datepicker default index is string value

I want to show datepicker default index value is string but I am not able to do that. Please suggest any idea. Thanks in advance.
I want to show picker like this:
You can use a UITextField and add date picker as a Input vie. And set PlaceHolder as "Date" or any string you want.
Sample Code
UITextField TextInput = new UITextField();
TextInput.Frame = new CGRect(40, 280, View.Frame.Width - 80, 40);
TextInput.Placeholder = "Date";
var picker = new UIDatePicker();
TextInput.InputView = picker;
Here is an example how to do it in ViewCell. You can use similar idea with View
public class TimePickerInCellPage : ContentPage
{
private ListView _listView;
public TimePickerInCellPage()
{
_listView = new ListView
{
RowHeight = 80,
SeparatorColor = Color.Blue,
SeparatorVisibility = SeparatorVisibility.Default
};
_listView.ItemsSource = new List<TaskTime>() {
new TaskTime { Id=1, StartTime=TimeSpan.FromHours(3) } ,
new TaskTime { Id=1, StartTime=TimeSpan.FromHours(5) } ,
new TaskTime { Id=1, StartTime=TimeSpan.FromHours(7) } ,
};
_listView.ItemTemplate = new DataTemplate(typeof(MyCell));
Content = new StackLayout
{
VerticalOptions = LayoutOptions.FillAndExpand,
Children = { _listView }
};
}
}
public class TaskTime
{
public int Id { get; set; }
public string Task { get; set; }
public TimeSpan StartTime { get; set; }
}
class MyCell : ViewCell
{
private readonly DatePicker _myTimePicker;
//private readonly TimePicker _myTimePicker;
public MyCell()
{
//_myTimePicker = new TimePicker()
_myTimePicker = new DatePicker()
{
HorizontalOptions = LayoutOptions.EndAndExpand
};
//_myTimePicker.Format = "HH:mm:ss";
_myTimePicker.Format = "dd:MM:yy HH:mm:ss";
_myTimePicker.SetBinding(TimePicker.TimeProperty, "StartTime");
_myTimePicker.PropertyChanged += MyTimePicker_PropertyChanged;
//_myTimePicker.Focused += _myTimePicker_Focused;
var viewLayout = new StackLayout()
{
HorizontalOptions = LayoutOptions.StartAndExpand,
Orientation = StackOrientation.Horizontal,
Padding = new Thickness(20),
Children = { _myTimePicker }
};
View = viewLayout;
}
bool firstTimeSet; //set when initial binding happens
//private void _myTimePicker_Focused(object sender, FocusEventArgs e)
//{
// firstTimeSet=true;
//}
private void MyTimePicker_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
//if (e.PropertyName == TimePicker.TimeProperty.PropertyName)
if (e.PropertyName == DatePicker.DateProperty.PropertyName)
{
if (!firstTimeSet)
firstTimeSet = true;
else
{
int x = 0;
string s = _myTimePicker.Date.ToString("dd/MM/yy HH:mm:ss");
}
}
}
}

How to show image on imageview using webservices and json

I am using web service for showing image in imageview. But web service image show in SYSTEM.BYTE[] Format. So how to Convert or display the image in imageview in xamarin android application??
Webservice.asmx:
[WebMethod(MessageName = "BindHospName", Description = "Bind Hospital Name Control")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
[System.Xml.Serialization.XmlInclude(typeof(GetHospName))]
public string BindHosp(decimal SpecID)
{
JavaScriptSerializer objJss = new JavaScriptSerializer();
List<GetHospName> HospName = new List<GetHospName>();
try
{
ConnectionString();
cmd = new SqlCommand("select b.HID,b.HospName,b.Logo from HospitalRegBasic b inner join HospitalRegClinical c on b.HID=c.HID " +
"where b.EmailActivationCode <> '' and b.EmailActivationStatus = 1 and b.Status = 1 and c.SPEC_ID = #SpecID ", conn);
cmd.Parameters.AddWithValue("#SpecID", SpecID);
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
var getHosp = new GetHospName
{
HospID = dr["HID"].ToString(),
HospName = dr["HospName"].ToString(),
HospLogo = dr["Logo"].ToString()
};
HospName.Add(getHosp);
}
}
dr.Close();
cmd.Dispose();
conn.Close();
}
catch (Exception)
{
throw;
}
return objJss.Serialize(HospName);
}
Class.cs:
namespace HSAPP
{
class ContListViewHospNameClass : BaseAdapter<GetHospNames>
{
List<GetHospNames> objList;
Activity objActivity;
public ContListViewHospNameClass (Activity objMyAct, List<GetHospNames> objMyList) : base()
{
this.objActivity = objMyAct;
this.objList = objMyList;
}
public override GetHospNames this[int position]
{
get
{
return objList[position];
}
}
public override int Count
{
get
{
return objList.Count;
}
}
public override long GetItemId(int position)
{
return position;
}
public static Bitmap bytesToBitmap(byte[] imageBytes)
{
Bitmap bitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
return bitmap;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = objList[position];
if (convertView == null)
{
convertView = objActivity.LayoutInflater.Inflate(Resource.Layout.ContListViewHospName, null);
}
convertView.FindViewById<TextView>(Resource.Id.tvHospID).Text = item.HospID;
convertView.FindViewById<TextView>(Resource.Id.tvHospName).Text = item.HospName;
byte[] img =item.HospLogo;
Bitmap bitmap = BitmapFactory.DecodeByteArray(img, 0, img.Length);
convertView.FindViewById<ImageView>(Resource.Id.imgLogo).SetImageBitmap(bitmap);
return convertView;
}
}
}
This is JSON Code:
private void BindControl_BindHospCompleted(object sender, BindControl.BindHospCompletedEventArgs e)
{
jsonValue = e.Result.ToString();
if (jsonValue == null)
{
Toast.MakeText(this, "No Data For Bind", ToastLength.Long).Show();
return;
}
try
{
JArrayValue = JArray.Parse(jsonValue);
list = new List<GetHospNames>();
int count = 0;
while (count < JArrayValue.Count)
{
GetHospNames getHospName = new GetHospNames(JArrayValue[count]["HospID"].ToString(), JArrayValue[count]["HospName"].ToString(),JArrayValue[count]["Logo"]);
list.Add(getHospName);
count++;
}
listView.Adapter = new ContListViewHospNameClass(this, list);
}
catch (Exception ex)
{
Toast.MakeText(this, ex.ToString(), ToastLength.Long).Show();
}
}
public static void SetImageFromByteArray (byte[] iArray, UIImageView imageView)
{
if (iArray != null && iArray.Length > 0) {
Bitmap bitmap = BitmapFactory.DecodeByteArray (iArray, 0, iArray.Length);
imageView.SetImageBitmap (bitmap);
}
}
That's it. If this is not working, your byte array may not be a valid image.
public static bool IsValidImage(byte[] bytes)
{
try {
using(MemoryStream ms = new MemoryStream(bytes))
Image.FromStream(ms);
}
catch (ArgumentException) {
return false;
}
return true;
}

Resources