MvvmCross: Binding warning on iOS device - ios

I´ve created my bindings like Stuart told in this Post: MvvmCross - How to bind UIView.Layer.AnyProperty (Xamarin.iOS) to a property on a viewmodel?
This works well on simulator, but not on a iOS device. I already added LinkerPleaseInclude.cs but this changed nothing.
Binding to BorderWidth works perfectly, binding to BorderColor shows a warning.
LinkerPleaseInclude.cs:
public class LinkerPleaseInclude
{
public void Include(UIButton uiButton)
{
uiButton.TouchUpInside += (s, e) =>
uiButton.SetTitle(uiButton.Title(UIControlState.Normal), UIControlState.Normal);
}
public void Include(UIBarButtonItem barButton)
{
barButton.Clicked += (s, e) =>
barButton.Title = barButton.Title + "";
}
public void Include(UITextField textField)
{
textField.Text = textField.Text + "";
textField.EditingChanged += (sender, args) => { textField.Text = ""; };
}
public void Include(UITextView textView)
{
textView.Text = textView.Text + "";
textView.Changed += (sender, args) => { textView.Text = ""; };
}
public void Include(UILabel label)
{
label.Text = label.Text + "";
}
public void Include(UIImageView imageView)
{
imageView.Image = new UIImage();
}
public void Include(UIDatePicker date)
{
date.Date = date.Date.AddSeconds(1);
date.ValueChanged += (sender, args) => { date.Date = DateTime.MaxValue.ToNSDate(); };
}
public void Include(UISlider slider)
{
slider.Value = slider.Value + 1;
slider.ValueChanged += (sender, args) => { slider.Value = 1; };
}
public void Include(UISwitch sw)
{
sw.On = !sw.On;
sw.ValueChanged += (sender, args) => { sw.On = false; };
}
public void Include(INotifyCollectionChanged changed)
{
changed.CollectionChanged += (s,e) => { var test = string.Format("{0}{1}{2}{3}{4}", e.Action,e.NewItems, e.NewStartingIndex, e.OldItems, e.OldStartingIndex); } ;
}
}
My code for binding:
bindingSet.Bind(this.MyUITextField.Layer)
.For(x => x.BorderColor)
.To(x => x.MyViewModelProperty.IsValid)
.WithConversion("ValidationStyleBorderColor");
bindingSet.Bind(this.MyUITextField.Layer)
.For(x => x.BorderWidth)
.To(x => x.MyViewModelProperty.IsValid)
.WithConversion("ValidationStyleBorderWidth");
bindingSet.Apply();
My converter:
public class ValidationStyleBorderColorValueConverter : MvxValueConverter<bool, CGColor>
{
protected override CGColor Convert(bool value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value == true ? Themes.Default.HighlightColor.CGColor : Themes.Default.ErrorColor.CGColor;
}
}
And the warning: MvxBind: Warning: 22,91 Failed to create target binding for binding BorderColor for MyViewModelProperty.IsValid
What am I doing wrong?

As Stuart told, including the Border properties in LinkerPleaseInclude made it.

Related

Listview Filter with SearchView Using Base Adapter in Xamarin android Error

I am try to filter listview with searchview using Base Adapter in in xamarin Android, My listView Bind in sql server using restfull web service i am stuck in PublishResults which is given an error
Here Is My Code:-
GetHospNames.cs
public class GetHospNames
{
public string HospID { get; set; }
public string HospName { get; set; }
public GetHospNames(string HospID, string HospName)
{
this.HospID = HospID;
this.HospName = HospName;
//this.HospLogo = HospLogo;
}
}
ContListViewHospNameClass.cs
using System.Collections.Generic;
using Android.App;
using Android.Views;
using Android.Widget;
using System;
using Android.Graphics;
using Android.Graphics.Drawables;
using System.IO;
using Android.Content;
using Java.Lang;
using Android.Text;
using Java.Util;
using Oject = Java.Lang.Object;
namespace HSAPP
{
public class ContListViewHospNameClass : BaseAdapter<GetHospNames>, IFilterable
{
public List<GetHospNames> objList;
Activity objActivity;
List<GetHospNames> filterList;
public ContListViewHospNameClass(Activity objMyAct, List<GetHospNames> objMyList) : base()
{
this.objActivity = objMyAct;
objList = objMyList;
this.filterList = objList;
Filter = new CustomFilter(this);
}
public override GetHospNames this[int position]
{
get
{
return objList[position];
}
}
public override int Count
{
get
{
return objList.Count;
}
}
public Filter Filter { get; set; }
public override void NotifyDataSetChanged()
{
base.NotifyDataSetChanged();
}
//This is Inner Class
public class CustomFilter : Filter
{
ContListViewHospNameClass CustomAdapter;
public CustomFilter(ContListViewHospNameClass adapter) : base()
{
this.CustomAdapter = adapter;
}
protected override FilterResults PerformFiltering(ICharSequence constraint)
{
FilterResults result = new FilterResults();
if (constraint != null && constraint.Length() > 0)
{
//Contraint To Upper
List<GetHospNames> filter = new List<GetHospNames>();
foreach (GetHospNames name in CustomAdapter.objList)
{
if (name.HospName.ToUpper().Contains(constraint.ToString().ToUpper()))
{
filter.Add(name);
}
}
Oject[] Name;
Name = new Oject[filter.Count];
for (int i = 0; i < filter.Count; i++)
{
Name[i] = filter[i].HospName.ToString();
}
result.Count = filter.Count;
result.Values = Name;
}
return result;
}
protected override void PublishResults(ICharSequence constraint, Filter.FilterResults result)
{
List<GetHospNames> filteredList = new List<GetHospNames>();
for (int i = 0; i < ((Oject[])result.Values).Length; i++)
{
filteredList.Add((Oject[])result.Values[i]);//Here Is An Error *****Cannot apply indexing with [] to an expression of type 'Object'****
}
CustomAdapter.objList = filteredList;
CustomAdapter.NotifyDataSetChanged();
}
}
public override long GetItemId(int position)
{
return position;
}
public Bitmap getBitmap(byte[] getByte)
{
if (getByte.Length != 0)
{
return BitmapFactory.DecodeByteArray(getByte, 0, getByte.Length);
}
else
{
return null;
}
}
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;
return convertView;
}
}
public static class ObjectTypeHelper
{
public static T Cast<T>(this Java.Lang.Object obj) where T : class
{
var propertyInfo = obj.GetType().GetProperty("Instance");
return propertyInfo == null ? null : propertyInfo.GetValue(obj, null) as T;
}
}
}
This is my MainActivity Code
private void BindControl_BindHospCompleted(object sender, BindControl.BindHospCompletedEventArgs e)
{
jsonValue = e.Result.ToString();
try
{
if (jsonValue == null)
{
Toast.MakeText(this, "No Data For Bind", ToastLength.Long).Show();
return;
}
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());
list.Add(getHospName);
count++;
}
if (count == 0)
{
Toast.MakeText(this, "No List Of Hospitals", ToastLength.Long).Show();
}
adapter = new ContListViewHospNameClass(this, list);
listView.Adapter = adapter;
search.QueryTextChange += (s, e) =>
{
adapter.Filter.InvokeFilter(e.NewText);
};
listView.ItemClick += ListView_ItemClick;
pBar.Dismiss();
}
catch (Java.Lang.Exception ex)
{
pBar.Dismiss();
//Toast.MakeText(this, ex.ToString(), ToastLength.Long).Show();
Finish();
Intent intent = new Intent(this, typeof(ChkIntConnActivity));
StartActivity(intent);
}
}
Please Help...Thank You

Xamarin Form: Ios Toast Notification

I have created a Toast notification in my Xamarin PCL project. I have created this control using this. As soon as this toast message disappears my app becomes blank. I cannot figure out why? no exception from any where??
In Portable:
namespace ABC
{
public interface IMessage
{
void LongAlert(string message);
void ShortAlert(string message);
}
}
In Droid:
public class MessageAndroid : IMessage
{
public void LongAlert(string message)
{
Toast.MakeText(Application.Context, message, ToastLength.Long).Show();
}
public void ShortAlert(string message)
{
Toast.MakeText(Application.Context, message, ToastLength.Short).Show();
}
}
In Windows 10:
public class ToastNotificationManagerRenderer : IMessage
{
public void LongAlert(string message)
{
var notificationXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
var toeastElement = notificationXml.GetElementsByTagName("text");
toeastElement[0].AppendChild(notificationXml.CreateTextNode(message));
var toastNotification = new ToastNotification(notificationXml);
ToastNotificationManager.CreateToastNotifier().Show(toastNotification);
}
public void ShortAlert(string message)
{
var notificationXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
var toeastElement = notificationXml.GetElementsByTagName("text");
toeastElement[0].AppendChild(notificationXml.CreateTextNode(message));
var toastNotification = new ToastNotification(notificationXml);
ToastNotificationManager.CreateToastNotifier().Show(toastNotification);
}
}
In Ios:
public class MessageIOS : IMessage
{
const double LONG_DELAY = 3.5;
const double SHORT_DELAY = 2.0;
NSTimer alertDelay;
UIAlertController alert;
public void LongAlert(string message)
{
ShowAlert(message, LONG_DELAY);
}
public void ShortAlert(string message)
{
ShowAlert(message, SHORT_DELAY);
}
void ShowAlert(string message, double seconds)
{
alertDelay = NSTimer.CreateScheduledTimer(seconds, (obj) =>
{
dismissMessage();
});
alert = UIAlertController.Create(null, message, UIAlertControllerStyle.Alert);
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alert, true, null);
}
void dismissMessage()
{
if (alert != null)
{
alert.DismissViewController(true, null);
}
if (alertDelay != null)
{
alertDelay.Dispose();
}
}
}
For Ios: I have tried this plugin also.MessageBarLib. Code same as above in portable but in Ios -
public void ShortAlert(string message)
{
MessageBarManager.SharedInstance.ShowMessage("Success", message, MessageType.Success);
}
But after exiting from above function, my app closes.
Based off of your comments and the code, I suspect that the dismissMessage()' is clearing all of the UIViewControllers that were put onto the stack by the 'PresentingViewController'. I suspect it's a bit of a bug, but If you try:
PresentingViewController.DismissViewController(true, null);
Instead of
alert.DismissViewController(true, null);
I suspect it should work correctly. If not then we could do with knowing a bit more about the design pattern you use in your iOS project to determine if you are presenting 'UIViewControllers' properly.
I tried this for IOS:-
private const int Margin = 30;
private const int Height = 40;
private const int Width = 400;
private NSTimer _timer;
public void ShowAlert(string message)
{
var toast = new MessageIOS();
toast.Show(UIApplication.SharedApplication.KeyWindow.RootViewController.View, message);
}
public MessageIOS()
{
_view = new UIView(new CGRect(0, 0, 0, 0))
{
BackgroundColor = UIColor.FromRGB(0, 175, 240)
};
_view.Layer.CornerRadius = (nfloat)20.0;
_label = new UILabel(new CGRect(0, 0, 0, 0))
{
TextAlignment = UITextAlignment.Center,
TextColor = UIColor.White
};
_view.AddSubview(_label);
}
public void Show(UIView parent, string message)
{
if (_timer != null)
{
_timer.Invalidate();
_view.RemoveFromSuperview();
}
_view.Alpha = (nfloat)0.7;
_view.Frame = new CGRect(
(parent.Bounds.Width - Width) / 2,
parent.Bounds.Height - Height - Margin,
Width,
Height);
_label.Frame = new CGRect(0, 0, Width, Height);
_label.Text = message;
parent.AddSubview(_view);
var wait = 10;
_timer = NSTimer.CreateRepeatingScheduledTimer(TimeSpan.FromMilliseconds(100), delegate {
if (_view.Alpha <= 0)
{
_timer.Invalidate();
_view.RemoveFromSuperview();
}
else
{
if (wait > 0)
{
wait--;
}
else
{
_view.Alpha -= (nfloat)0.05;
}
}
});
}

Updating image control in Windows Phone 8

I have a HTML5 web app I can view through my mobile devices.
I have an img control that would download an image using an ashx asp.net handler.
I updated via a timer.
I am trying to port this over to a Windows Phone 8.1 app instead.
The image seems to take ages to update (if at all). This is my code:
long tick = DateTime.Now.Ticks;
BitmapImage bmp =new BitmapImage(new Uri("http://my url/Mobile/NewFrame.ashx?b=1a=9A5C3-E1945-3D315-BB43C&c=3&m=1&t=" + tick));
imgFrame1.Source = bmp;
Is this the correct way?
this is the full code:
private async void LogIn()
{
using (var client = new HttpClient())
{
var resp = await client.PostAsJsonAsync("http://my url/UserManagement/Login.aspx/Test",
new { username = "", password = "", hubuserid = hubuserid });
var str = await resp.Content.ReadAsStringAsync();
var jsonObj = JsonConvert.DeserializeObject<UserLogIn>(str);
if (jsonObj.d.Success)
{
UpdateConnectionState("Logged In");
}
else
{
UpdateConnectionState("Not Logged In");
}
}
}
public class D
{
public string __type { get; set; }
public bool Success { get; set; }
}
public class UserLogIn
{
public D d { get; set; }
}
private string hubuserid = "";
public string Uptime { get; set; }
private byte ImageIsLoaded = 1;
private async void UpdateTime(int data)
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
try
{
txtInfo.Text = data.ToString();
if (ImageIsLoaded == 1)
{
ImageIsLoaded = 0;
long tick = DateTime.Now.Ticks;
BitmapImage bi = new BitmapImage(new Uri("http://www.informedmotion.co.uk/Mobile/NewFrame.ashx?b=1a=9A5C3-E1945-3D315-BB43C&c=3&m=1&t=" + tick, UriKind.Absolute));
bi.DownloadProgress += bi_DownloadProgress;
bi.ImageOpened += bi_ImageOpened; }
}
catch (Exception ex)
{
txtInfo.Text = ex.ToString();
}
});
}
void bi_DownloadProgress(object sender, DownloadProgressEventArgs e)
{
//throw new NotImplementedException();
}
void bi_ImageOpened(object sender, RoutedEventArgs e)
{
ImageIsLoaded = 1;
imgFrame1.Source = (BitmapImage)sender;
}
private void imgFrame1_ImageOpened(object sender, RoutedEventArgs e)
{
ImageIsLoaded = 1;
}
private void imgFrame1_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
ImageIsLoaded = 1;
}
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
imgFrame1.ImageFailed += imgFrame1_ImageFailed;
imgFrame1.ImageOpened += imgFrame1_ImageOpened;
ConnectToHub();
}
private void ConnectToHub()
{
proxy.On<int>("broadcastMessage", data =>
{
UpdateTime(data);
});
connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
UpdateConnectionState("Not Connected");
ConnectToHub();
}
else
{
UpdateConnectionState(string.Format("Success! Connected with client connection id {0}", connection.ConnectionId));
hubuserid = connection.ConnectionId;
LogIn();
}
});
connection.Error += ex =>
{
UpdateConnectionState(string.Format("An error occurred {0}", ex.Message));
};
connection.Closed += () =>
{
UpdateConnectionState(string.Format("Connection with client id {0} closed", connection.ConnectionId));
ConnectToHub();
};
connection.Reconnected += () =>
{
//LogIn();
UpdateConnectionState("The connection was re-established");
};
}
Windows.UI.Core.CoreDispatcher dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
async void UpdateConnectionState(string state)
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
try{
txtInfo.Text = state;
}
catch (Exception ex)
{
txtInfo.Text = ex.ToString();
}
});
}
static HubConnection connection = new HubConnection("http://www.informedmotion.co.uk/");
IHubProxy proxy = connection.CreateHubProxy("ChatHub");
If you're going to download the image, then you probably want to hooked the
Image.DownloadProgress event
Image.ImageOpened event
ImageOpened will fire once the download is complete, so at that moment you can set the .Source to it.
While it is downloading (if it's a huge image) you can either show the previous image or a place holder image (with progress bar maybe?)
BitmapImage bi = new BitmapImage(new Uri("http://www.google.com/myimage.bmp", UriKind.Absolute));
bi.DownloadProgress += bi_DownloadProgress;
bi.ImageOpened += bi_ImageOpened;
hiddenImage.Source = bi; // we need to set it to an element in the visual tree so the
// events will fire, we're going to use the hiddenImage
void bi_DownloadProgress(object sender, DownloadProgressEventArgs e)
{
throw new NotImplementedException();
}
void bi_ImageOpened(object sender, RoutedEventArgs e)
{
throw new NotImplementedException();
}
<!-- myImage is your image that you use to show stuff -->
<!-- hiddenImage is the image we use to fire the event -->
<Image x:Name="myImage"></Image>
<Image x:Name="hiddenImage" Visibility="Collapsed"></Image>

Clickhandler to delete an tablerow

I'm building an app were i add tablerows to a view programmatically. I add a deletebutton to every row that is an ImageButton. Now i have a few questions.
Can i use an ImageButton for this?
How do i get the tablerow id
where the deletebutton was clicked?
How can i convert the eventargs
from a clickhandler into MenuItemOnMenuItemClickEventArgs or vice
versa?
How should my clickhandler look like?
Here is my sourcecode:
public class CalculatorSide2 : Activity
{
private Button stepButton;
private IntentHelper intentHelper = new IntentHelper();
private string age;
private string estLife;
private string estPens;
private string[] pensions;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
intentHelper.IntentSide2(Intent, out age, out estLife,out estPens);
SetContentView(Resource.Layout.calculatorside2);
TableLayout tl_layout = FindViewById<TableLayout>(Resource.Id.tableLayout1);
ImageView plusButton = FindViewById<ImageView>(Resource.Id.plusButton);
stepButton = FindViewById<Button>(Resource.Id.cside2stepButton);
plusButton.Click += (sender, e) =>
{
PopupMenu popupMenu = new PopupMenu(this, plusButton);
popupMenu.Inflate(Resource.Menu.popupmenu);
fillPopupMenu(popupMenu);
popupMenu.Show();
popupMenu.MenuItemClick += (s1, arg) =>
{
string info = arg.Item.TitleFormatted.ToString();
string id = arg.Item.ItemId.ToString();
var inputDialog = new AlertDialog.Builder(this);
EditText userInput = new EditText(this);
userInput.InputType = (Android.Text.InputTypes.NumberFlagDecimal | Android.Text.InputTypes.ClassNumber);
inputDialog.SetTitle(info);
inputDialog.SetView(userInput);
inputDialog.SetPositiveButton("Ok", (ss, ee) =>
{
TextView rowInfo = new TextView(this);
rowInfo.SetLines(2);
rowInfo.TextSize = 20;
rowInfo.SetTextColor(Android.Graphics.Color.Black);
rowInfo.Text = info + ": \n" + userInput.Text + "€";
ImageButton delete = new ImageButton(this);
delete.SetBackgroundDrawable(Resources.GetDrawable(Resource.Drawable.delete_icon));
TableRow row = new TableRow(this);
row.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
row.SetBackgroundColor(Android.Graphics.Color.Rgb(255, 153, 0));
row.SetPadding(0, 0, 0, 30);
row.AddView(rowInfo);
row.AddView(delete);
tl_layout.AddView(row);
});
inputDialog.SetNegativeButton("Cancel", (se, es) => { });
inputDialog.Show();
};
};
stepButton.Click += (object sender, EventArgs e) =>
{
var step = new Intent(this, typeof(CalculatorSide3));
step.PutExtra("Age", age);
step.PutExtra("EstPens", estPens);
step.PutExtra("EstLife", estLife);
step.PutStringArrayListExtra("Pensions", pensions);
StartActivity(step);
};
}
private void fillPopupMenu(PopupMenu menu)
{
int groupId = 0;
int i = 0;
int menuItemId = Android.Views.Menu.First;
int menuItemOrder = Android.Views.Menu.None;
foreach (var item in Enum.GetNames(typeof(PopupMenuItems)))
{
string itemString = item.ToString();
menu.Menu.Add(groupId, menuItemId + i, menuItemOrder + i, itemString.Replace("_", " "));
i++;
}
}
}
I hope someone understands what i mean, bc english is not my native language.
public class CalculatorSide2 : Activity
{
private Button stepButton;
private IntentHelper intentHelper = new IntentHelper();
private string age;
private string estLife;
private string estPens;
private string[] pensions;
private Dictionary<int,string> temp;
private TableLayout tl_layout;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
intentHelper.IntentSide2(Intent, out age, out estLife,out estPens);
SetContentView(Resource.Layout.calculatorside2);
tl_layout = FindViewById<TableLayout>(Resource.Id.tableLayout1);
ImageView plusButton = FindViewById<ImageView>(Resource.Id.plusButton);
stepButton = FindViewById<Button>(Resource.Id.cside2stepButton);
temp = new Dictionary<int,string>();
int i = 0;
plusButton.Click += (sender, e) =>
{
PopupMenu popupMenu = new PopupMenu(this, plusButton);
popupMenu.Inflate(Resource.Menu.popupmenu);
fillPopupMenu(popupMenu);
popupMenu.Show();
popupMenu.MenuItemClick += (s1, arg) =>
{
string info = arg.Item.TitleFormatted.ToString();
string id = arg.Item.ItemId.ToString();
var inputDialog = new AlertDialog.Builder(this);
EditText userInput = new EditText(this);
userInput.InputType = (Android.Text.InputTypes.NumberFlagDecimal | Android.Text.InputTypes.ClassNumber);
inputDialog.SetTitle(info);
inputDialog.SetView(userInput);
inputDialog.SetPositiveButton("Ok", (ss, ee) =>
{
TextView rowInfo = new TextView(this);
rowInfo.SetLines(2);
rowInfo.TextSize = 20;
rowInfo.SetTextColor(Android.Graphics.Color.Black);
rowInfo.Text = info + ": \n" + userInput.Text + "€";
ImageButton delete = new ImageButton(this);
delete.SetBackgroundDrawable(Resources.GetDrawable(Resource.Drawable.delete_icon));
delete.Focusable = false;
delete.Clickable = false;
TableRow row = new TableRow(this);
row.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
row.SetBackgroundColor(Android.Graphics.Color.Rgb(255, 153, 0));
row.SetPadding(0, 0, 0, 30);
row.Id = 10 + i;
row.Click += new EventHandler(HandleClick);
row.AddView(rowInfo);
row.AddView(delete);
tl_layout.AddView(row);
temp.Add(row.Id,userInput.Text);
i++;
});
inputDialog.SetNegativeButton("Cancel", (se, es) => { });
inputDialog.Show();
};
};
stepButton.Click += (object sender, EventArgs e) =>
{
if (temp.Count != 0)
{
pensions = new string[temp.Count];
var j = 0;
foreach (KeyValuePair<int, string> pair in temp)
{
pensions[j] = pair.Value;
j++;
}
}
else
{
pensions = new string[0];
}
var step = new Intent(this, typeof(CalculatorSide3));
step.PutExtra("Age", age);
step.PutExtra("EstPens", estPens);
step.PutExtra("EstLife", estLife);
step.PutStringArrayListExtra("Pensions", pensions);
StartActivity(step);
};
}
private void fillPopupMenu(PopupMenu menu)
{
int groupId = 0;
int i = 0;
int menuItemId = Android.Views.Menu.First;
int menuItemOrder = Android.Views.Menu.None;
foreach (var item in Enum.GetNames(typeof(PopupMenuItems)))
{
string itemString = item.ToString();
menu.Menu.Add(groupId, menuItemId + i, menuItemOrder + i, itemString.Replace("_", " "));
i++;
}
}
public void HandleClick(object sender, EventArgs e)
{
var clickedTR = sender as TableRow;
int trId = clickedTR.Id;
var builder = new AlertDialog.Builder(this);
builder.SetTitle("Löschen");
builder.SetMessage("Möchten Sie den Eintrag wirklich löschen?");
builder.SetPositiveButton("Ja", (ssr,args) => {
temp.Remove(trId);
tl_layout.RemoveView(clickedTR);
});
builder.SetNegativeButton("Nein",(sse,arge) => { });
builder.SetCancelable(false);
builder.Show();
}
}

how to use multi choice spinner in mono for android?

I want to use multi choice spinner in mono for android.
I want to bind the countries to the spinner
Now in the normal spinner there is label with radio button.
But I want the label with the Checkbox.
can any one please help me.
AlertDialog.Builder alt_bld = new AlertDialog.Builder(
CareCardActivity.this);
alt_bld.setTitle("Select Recepients");
alt_bld.setMultiChoiceItems(tempname, new boolean[tempname.length] , new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
// TODO Auto-generated method stub
}
});
alt_bld.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
ListView list = ((AlertDialog) dialog).getListView();
Log.v("LIST COUNT:: ", ""+list.getCount());
for (int i = 0; i < list.getCount(); i++) {
boolean checked = list.isItemChecked(i);
if (checked) {
sb.append(contactNumber[i]).append(";");
}
}
sb = sb.replace(
sb.length() - 1,
sb.length(), "");
txtPhoneNo.setText(sb.toString());
}
});
alt_bld.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
AlertDialog alert = alt_bld.create();
alert.show();
I have tried this code in the eclipse it is working fine in it, but I want to do it for Mono develop in C#.
call this function on click of button
ShowDialog(DIALOG_MULTIPLE_CHOICE);
Add Following Code
protected override Dialog OnCreateDialog(int id)
{
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, OnDateSet, date.Year, date.Month - 1, date.Day);
case DIALOG_MULTIPLE_CHOICE: {
var builder = new AlertDialog.Builder (this);
// builder.SetIcon (Resource.Drawable.ic_popup_reminder);
builder.SetTitle ("Select Country");
builder.SetMultiChoiceItems (countryName, new bool[countryName.Length], MultiListClicked);
builder.SetPositiveButton ("ok", OkClicked);
builder.SetNegativeButton ("Cancel", CancelClicked);
return builder.Create ();
}
}
return null;
}
private void MultiListClicked (object sender, DialogMultiChoiceClickEventArgs e)
{
Console.WriteLine ("countryMultiListClicked");
if (e.IsChecked) {
mSelectedItems.Add (countryName [(int)e.Which]);
mSelectedItemsID.Add (countryID [(int)e.Which]);
}
else if (mSelectedItems.Contains(countryName [(int)e.Which]))
{
mSelectedItems.Remove(countryName [(int)e.Which]);
mSelectedItemsID.Remove(countryID [(int)e.Which]);
}
}
private void OkClicked (object sender, DialogClickEventArgs e)
{
Console.WriteLine ("countryOkClicked");
String listString = "";
for (int i =0; i<mSelectedItems.Count; i++) {
listString += mSelectedItems [i] + ",";
}
if (listString.Length > 0) {
listString = listString.Remove (listString.Length - 1);
}
et_country.Text = listString;
listStringId = "";
for (int i =0; i<mSelectedItemsID.Count; i++) {
listStringId += mSelectedItemsID [i] + ",";
}
if (listStringId.Length > 0) {
listStringId = listStringId.Remove (listStringId.Length - 1);
}
Console.WriteLine (listStringId);
}
private void CancelClicked (object sender, DialogClickEventArgs e)
{
Console.WriteLine("countryCancelClicked");
}
This works fine ........!

Resources