async Task GetSendSMSPermissionAsync() { //Check to see if any permission in our group is available, if one, then all are const string permission = Manifest.Permission.SendSms; if (CheckSelfPermission(Manifest.Permission.SendSms) == (int)Permission.Granted) { await SMSSend(); return; } //need to request permission if (ShouldShowRequestPermissionRationale(permission)) { var callDialog = new AlertDialog.Builder(this); callDialog.SetTitle("explain"); callDialog.SetMessage("This app needt to send sms so it need sms send permission"); callDialog.SetNeutralButton("yes", delegate { RequestPermissions(PermissionsLocation, RequestLocationId); }); callDialog.SetNegativeButton("no", delegate { }); callDialog.Show(); return; } //Finally request permissions with the list of permissions and Id RequestPermissions(PermissionsLocation, RequestLocationId); }
public void SetTitle(string title) { if (_useAppCompat) { _appcompatBuilder?.SetTitle(title); } else { _legacyBuilder?.SetTitle(title); } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.Detalles); try { SidG = (Intent.GetStringExtra("idG")); SiduS = (Intent.GetStringExtra("idUS")); idUs = Convert.ToInt32(SiduS); idG = Convert.ToInt32(SidG); } catch (Exception ex) { AlertDialog alerta = new AlertDialog.Builder(this).Create(); alerta.SetTitle("Error "); alerta.SetMessage(ex.Message + "'asdasd'"); alerta.SetButton("Aceptar", (a, b) => { }); alerta.Show(); } g = bd.buscar(idG); // referencia a obj del laout btnfecha = FindViewById <Button>(Resource.Id.fecha); btnfecha.Click += BtnFecha_Click; btnDesayunoAntes = FindViewById <Button>(Resource.Id.btnDesayunoAntes); btnDesayunoAntes.Click += BtnDesayunoAntes_Click; txt_des_antes = FindViewById <EditText>(Resource.Id.txt_des_antes); btnDesayunoDespues = FindViewById <Button>(Resource.Id.btnDesayunoDespues); btnDesayunoDespues.Click += BtnDesayunoDespues_Click; txt_des_Des = FindViewById <EditText>(Resource.Id.txt_des_Des); btnAlmuerzoAntes = FindViewById <Button>(Resource.Id.btnAlmuerzoAntes); btnAlmuerzoAntes.Click += BtnAlmuerzoAntes_Click; txt_alm_antes = FindViewById <EditText>(Resource.Id.txt_alm_antes); btnAlmuerzoDespues = FindViewById <Button>(Resource.Id.btnAlmuerzoDespues); btnAlmuerzoDespues.Click += BtnAlmuerzoDespues_Click; txt_alm_des = FindViewById <EditText>(Resource.Id.txt_alm_des); btnAntesCena = FindViewById <Button>(Resource.Id.btnAntesCena); btnAntesCena.Click += BtnAntesCena_Click; Txt_cen_Antes = FindViewById <EditText>(Resource.Id.Txt_cen_Antes); btnDespuesCena = FindViewById <Button>(Resource.Id.btnDespuesCena); btnDespuesCena.Click += BtnDespuesCena_Click; Txt_cen_Despues = FindViewById <EditText>(Resource.Id.Txt_cen_Despues); btnDormirAntes = FindViewById <Button>(Resource.Id.btnDormirAntes); btnDormirAntes.Click += BtnDormirAntes_Click; Txt_Dor_Antes = FindViewById <EditText>(Resource.Id.Txt_Dor_Antes); btnDormirDespues = FindViewById <Button>(Resource.Id.btnDormirDespues); btnDormirDespues.Click += BtnDormirDespues_Click; Txt_Dor_Despues = FindViewById <EditText>(Resource.Id.Txt_Dor_Despues); txt_obs = FindViewById <EditText>(Resource.Id.txt_obs); // insulina mnna_rap = FindViewById <EditText>(Resource.Id.mnna_rap); mnna_regul = FindViewById <EditText>(Resource.Id.mnna_regul); mnna_mezcla = FindViewById <EditText>(Resource.Id.mnna_mezcla); tarde_rap = FindViewById <EditText>(Resource.Id.tarde_rap); tarde_regul = FindViewById <EditText>(Resource.Id.tarde_regul); tarde_mezcla = FindViewById <EditText>(Resource.Id.tarde_mezcla); noche_rap = FindViewById <EditText>(Resource.Id.noche_rap); noche_regul = FindViewById <EditText>(Resource.Id.noche_regul); noche_mezcla = FindViewById <EditText>(Resource.Id.noche_mezcla); dormir_rap = FindViewById <EditText>(Resource.Id.dormir_rap); dormir_regul = FindViewById <EditText>(Resource.Id.dormir_regul); dormir_mezcla = FindViewById <EditText>(Resource.Id.dormir_mezcla); btn_actualizar = FindViewById <Button>(Resource.Id.btn_actualizar); btn_eliminar = FindViewById <Button>(Resource.Id.btn_eliminar); btn_actualizar.Click += ActualizarAsync; btn_eliminar.Click += Btn_eliminar_Click; llena_campos(); SetUpMap();// inicializacion del mapa }
internal void ShowPopUp(string positive, string negative) { alertBuilder.SetTitle("Enter Text"); editText.Text = _inputstring; editText.FocusableInTouchMode = true; editText.RequestFocus(); editText.SetBackgroundColor(Color.WhiteSmoke); editText.SetTextColor(Color.Black); alertBuilder.SetView(editText); alertBuilder.SetCancelable(false); alertBuilder.SetPositiveButton(positive, (senderAlert, args) => { diagram.Alpha = 1; diagram.PageSettings.BackgroundColor = Color.White; if (editText.Text == null) { editText.Text = ""; } var node = new Node(diagram.Context); if (CurrentHandle == UserHandlePosition.Left) { node.OffsetX = SelectedNode.OffsetX - SelectedNode.Width - 100; node.OffsetY = SelectedNode.OffsetY; } else if (CurrentHandle == UserHandlePosition.Right) { node.OffsetX = SelectedNode.OffsetX + SelectedNode.Width + 100; node.OffsetY = SelectedNode.OffsetY; } node.Width = SelectedNode.Width; node.Height = SelectedNode.Height; node.ShapeType = ShapeType.RoundedRectangle; node.Style.StrokeWidth = 3; if (SelectedNode == RootNode) { index = rnd.Next(5); node.Style.Brush = new SolidBrush(FColor[index]); node.Style.StrokeBrush = new SolidBrush(SColor[index]); } else { node.Style = SelectedNode.Style; } node.Annotations.Add(new Annotation() { Content = editText.Text, FontSize = 14 * MainActivity.Factor, TextBrush = new SolidBrush(Color.Black) }); diagram.AddNode(node); var c1 = new Connector(diagram.Context); c1.SourceNode = SelectedNode; c1.TargetNode = node; //c1.Style.StrokeBrush = node.Style.StrokeBrush; //c1.Style.StrokeWidth = 3; //c1.TargetDecoratorStyle.Fill = (node.Style.StrokeBrush as SolidBrush).FillColor; //c1.TargetDecoratorStyle.StrokeColor = (c1.TargetNode.Style.StrokeBrush as SolidBrush).FillColor; //c1.SegmentType = SegmentType.CurveSegment; //c1.Style.StrokeStyle = StrokeStyle.Dashed; diagram.AddConnector(c1); if (CurrentHandle == UserHandlePosition.Left) { if (!(diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm) { (diagram.LayoutManager.Layout as MindMapLayout).UpdateLeftOrTop(); } } else if (CurrentHandle == UserHandlePosition.Right) { if (!(diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm) { (diagram.LayoutManager.Layout as MindMapLayout).UpdateRightOrBottom(); } } m_mindmap.SelectedNode = node; m_mindmap.UpdateHandle(); diagram.Select(node); diagram.BringToView(node); m_mindmap.UpdateTheme(); }); alertBuilder.SetNegativeButton(negative, (senderAlert, args) => { alertBuilder.SetCancelable(true); }); alertBuilder.Show(); }
private async Task <bool> StartTest() { var rig = test.rig; var connections = test.connections.Values; var progress = new ProgressDialog(this); progress.SetTitle("Please Wait..."); progress.SetMessage("We are connecting to all of the devices. Please wait."); progress.Indeterminate = true; progress.SetCancelable(false); handler.Post(() => { progress.Show(); }); Action dismiss = new Action(() => { handler.Post(() => { progress.Dismiss(); }); }); // First we will need to connect to the rig var start = DateTime.Now; rig.Connect(); while (DateTime.Now - start <= TimeSpan.FromSeconds(30)) { if (rig.isConnected) { break; } else { await Task.Delay(TimeSpan.FromMilliseconds(150)); } } if (!rig.isConnected) { handler.Post(() => { var adb = new AlertDialog.Builder(this); adb.SetTitle("Failed to Start Test"); adb.SetMessage("Failed to connect to the test rig."); adb.SetNegativeButton("Well, then connect to the rig?!", (sender, e) => { }); adb.Show(); }); dismiss(); StopTest(); return(false); } var missingConnection = false; for (var attempts = 3; attempts >= 2; attempts--) { // Connect to all of the selected connections. foreach (var connection in connections) { handler.Post(() => { if (!connection.isConnected) { connection.Connect(); } }); await Task.Delay(TimeSpan.FromMilliseconds(2000)); } start = DateTime.Now; while (DateTime.Now - start <= TimeSpan.FromSeconds(20)) { missingConnection = false; foreach (var connection in connections) { if (!connection.isConnected) { missingConnection = true; break; } } if (!missingConnection) { break; } else { await Task.Delay(150); } } // Check if we need another try bool needsAnotherTry = false; foreach (var connection in connections) { if (!connection.isConnected) { connection.Disconnect(); needsAnotherTry = true; } } if (needsAnotherTry) { continue; } } dismiss(); if (!rig.isConnected) { missingConnection = true; } else { foreach (var connection in connections) { if (!connection.isConnected) { missingConnection = true; break; } } } if (missingConnection) { var sb = new StringBuilder(); sb.Append("Failed to connect to the following devices:\n"); if (!rig.isConnected) { sb.Append("TestRig, "); } foreach (var connection in connections) { if (!connection.isConnected) { sb.Append(connection.serialNumber).Append(", "); } } var adb = new AlertDialog.Builder(this); adb.SetTitle("Failed to Start Test"); adb.SetMessage(sb.ToString()); adb.SetCancelable(false); adb.SetNegativeButton("Cancel", (sender, e) => { }); adb.Show(); StopTest(); return(false); } else { test.StartTest(); return(true); } }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Window.AddFlags(WindowManagerFlags.KeepScreenOn); ActionBar.SetDisplayHomeAsUpEnabled(true); ActionBar.SetHomeButtonEnabled(true); SetContentView(Resource.Layout.activity_test); handler = new Handler(Looper.MainLooper); state = FindViewById <TextView>(Resource.Id.state); startTest = FindViewById <Button>(Resource.Id.startTest); startTest.Visibility = ViewStates.Gone; startTest.Click += async(sender, e) => { if (test.isTesting) { StopTest(); } else { await StartTest(); } }; var rawSerials = Intent.GetStringArrayExtra(EXTRA_SERIALS); var type = (EDeviceModel)Intent.GetIntExtra(EXTRA_TEST_TYPE, -1); if (rawSerials == null) { var adb = new AlertDialog.Builder(this); adb.SetTitle("Initialization Error"); adb.SetMessage("Failed to start TestActivity: no serial numbers were passed to the activity"); adb.SetNegativeButton("Cancel", (sender, e) => { Finish(); }); adb.Show(); } var sns = new List <ISerialNumber>(); foreach (var raw in rawSerials) { var sn = raw.ParseSerialNumber(); if (sn.deviceModel != type) { var adb = new AlertDialog.Builder(this); adb.SetTitle("Initialization Error"); adb.SetMessage("Failed to start TestActivity: serial number type (" + sn.deviceModel + ") is not the expected: " + type); adb.SetNegativeButton("Well, that sucks", (sender, e) => { Finish(); }); adb.Show(); return; } else { sns.Add(sn); } } grid = FindViewById <DSGridView>(Resource.Id.grid); grid.Theme = DSoft.Themes.Grid.DSGridTheme.Current; Initialize(); UpdateStartTestButton(); }
public void CreatePopup(object sender, RatingBar.RatingBarChangeEventArgs e) { try { Dialog editDialog = new Dialog(Parent); var rat = e.Rating; //editDialog.Window.RequestFeature(WindowFeatures.NoTitle); //editDialog.Window.SetBackgroundDrawable(new Android.Graphics.Drawables.ColorDrawable(Android.Graphics.Color.White));// (Android.Graphics.Color.Transparent)); editDialog.SetContentView(Resource.Layout.EditReviewPopup); //editDialog.SetTitle(); ServiceWrapper sw = new ServiceWrapper(); Review review = new Review(); ImageButton close = editDialog.FindViewById <ImageButton>(Resource.Id.close); Button btnSubmitReview = editDialog.FindViewById <Button>(Resource.Id.btnSubmitReview); TextView Comments = editDialog.FindViewById <TextView>(Resource.Id.txtReviewComments); RatingBar custRating = editDialog.FindViewById <RatingBar>(Resource.Id.rating); custRating.Rating = rat; Comments.Text = _editObj.RatingText; int screenid = 9; //ImageButton ibs = editDialog.FindViewById<ImageButton>(Resource.Id.ratingimage); //ItemReviewResponse SkuRating = new ItemReviewResponse(); //SkuRating = sw.GetItemReviewsByWineID(WineId).Result; //ReviewArray = SkuRating.Reviews.ToList(); //for (int i = 0; i < ReviewArray.Count(); i++) //{ // if (Convert.ToInt32(CurrentUser.getUserId()) == ReviewArray[i].ReviewUserId) // { // ItemReviewResponse uidreviews = new ItemReviewResponse(); // uidreviews = sw.GetItemReviewUID(Convert.ToInt32(CurrentUser.getUserId())).Result; // List<Review> myArr1; // myArr1 = uidreviews.Reviews.ToList(); // for (int j = 0; j < myArr1.Count; j++) // { // if (ReviewArray[i].Name == myArr1[i].Name) // Comments.Text = myArr1[i].RatingText.ToString(); // } // } // else // { // CreatePopup(sender, e); // } //} //ibs.SetImageResource(Resource.Drawable.wine_review); //ibs.SetScaleType(ImageView.ScaleType.CenterCrop); //close.SetImageResource(Resource.Drawable.Close); close.SetScaleType(ImageView.ScaleType.CenterCrop); editDialog.Window.SetBackgroundDrawable(new Android.Graphics.Drawables.ColorDrawable(Android.Graphics.Color.Transparent)); editDialog.Show(); LoggingClass.LogInfo("Entered into CreatePopup", screenid); close.Click += delegate { LoggingClass.LogInfo("Closed PoPup", screenid); editDialog.Dismiss(); }; btnSubmitReview.Click += async delegate { AndHUD.Shared.Show(Parent, "Saving Review...", Convert.ToInt32(MaskType.Clear)); if (CurrentUser.getUserId() == null) { AlertDialog.Builder aler = new AlertDialog.Builder(Parent, Resource.Style.MyDialogTheme); aler.SetTitle("Sorry"); aler.SetMessage("This Feature is available for VIP Users only"); aler.SetNegativeButton("Ok", delegate { LoggingClass.LogInfo("Closed PoPup", screenid); editDialog.Dismiss(); }); Dialog dialog1 = aler.Create(); dialog1.Show(); } else { //ProgressIndicator.Show(Parent); review.ReviewDate = DateTime.Now; review.ReviewUserId = Convert.ToInt32(CurrentUser.getUserId()); review.Username = CurrentUser.getUserName(); review.RatingText = Comments.Text; review.RatingStars = Convert.ToInt32(custRating.Rating); review.IsActive = true; review.Barcode = WineBarcode; review.PlantFinal = storeid; LoggingClass.LogInfo("Submitted review---->" + review.RatingStars + " ---->" + review.RatingText + "---->" + review.PlantFinal + "---->" + review.Barcode, screenid); await sw.InsertUpdateReview(review); ((IPopupParent)Parent).RefreshParent(); //ProgressIndicator.Hide(); editDialog.Dismiss(); } AndHUD.Shared.Dismiss(); AndHUD.Shared.ShowSuccess(Parent, "Sucessfully Saved", MaskType.Clear, TimeSpan.FromSeconds(2)); }; } catch (Exception exe) { LoggingClass.LogError(exe.Message, ParentScreenId, exe.StackTrace.ToString()); } //LoggingClass.LogTime("create popup",st.Elapsed.TotalSeconds.ToString()); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.Configuraciones); ISharedPreferences prefs = Application.Context.GetSharedPreferences("Settings", FileCreationMode.Private); ISharedPreferencesEditor prefEditor = prefs.Edit(); botonseleccionarcarpeta = FindViewById <Button>(Resource.Id.imageView1); localizacion = FindViewById <TextView>(Resource.Id.textView3); // botonguardar = FindViewById<ImageView>(Resource.Id.imageView2); var colormuestra = FindViewById <ImageView>(Resource.Id.imageView3); colormuestra.SetBackgroundColor(Color.ParseColor(SettingsHelper.GetSetting("color"))); color = SettingsHelper.GetSetting("color"); reprodautomatica = SettingsHelper.GetSetting("automatica"); var ll1 = FindViewById <LinearLayout>(Resource.Id.linearLayout3); var ll2 = FindViewById <LinearLayout>(Resource.Id.linearLayout4); var ll3 = FindViewById <LinearLayout>(Resource.Id.linearLayout5); var ll4 = FindViewById <LinearLayout>(Resource.Id.linearLayout7); var ll5 = FindViewById <LinearLayout>(Resource.Id.linearLayout23); var fondo = FindViewById <ImageView>(Resource.Id.fondo1); var toggle1 = FindViewById <Android.Support.V7.Widget.SwitchCompat>(Resource.Id.toggleButton1); var toggle2 = FindViewById <Android.Support.V7.Widget.SwitchCompat>(Resource.Id.toggleButton2); var automatica = FindViewById <Android.Support.V7.Widget.SwitchCompat>(Resource.Id.automatico); var botonclearcache = FindViewById <LinearLayout>(Resource.Id.linearLayout8); calidades = FindViewById <Spinner>(Resource.Id.spinner1); var action = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.my_toolbar); //////////////////////////////////////coloreselector mappings #pragma warning disable CS0618 // El tipo o el miembro están obsoletos dialogoprogreso = new ProgressDialog(this); #pragma warning restore CS0618 // El tipo o el miembro están obsoletos /////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// /// if (reprodautomatica == "si") { automatica.Checked = true; } else { automatica.Checked = false; } SetSupportActionBar(action); SupportActionBar.Title = "Preferencias"; SupportActionBar.SetDisplayHomeAsUpEnabled(true); var adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem); adapter.AddAll(new string[] { "Audio", "360p", "720p" }.ToList()); adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); calidades.Adapter = adapter; color = SettingsHelper.GetSetting("color"); calidad = int.Parse(SettingsHelper.GetSetting("video")); switch (calidad) { case -1: calidades.SetSelection(0); break; case 360: calidades.SetSelection(1); break; case 720: calidades.SetSelection(2); break; } if (SettingsHelper.HasKey("abrirserver")) { abrirserver = SettingsHelper.GetSetting("abrirserver"); } if (abrirserver == "no") { toggle2.Checked = false; } else { toggle2.Checked = true; } if (SettingsHelper.HasKey("ordenalfabeto")) { ordenalfabeto = SettingsHelper.GetSetting("ordenalfabeto"); if (ordenalfabeto == "si") { toggle1.Checked = true; } else { toggle1.Checked = false; } } if (SettingsHelper.HasKey("rutadescarga")) { klk = prefs.GetString("rutadescarga", null); } else { if (Directory.Exists(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/YTDownloads")) { klk = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/YTDownloads"; prefEditor.PutString("rutadescarga", klk); prefEditor.Commit(); } else { Directory.CreateDirectory(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/YTDownloads"); klk = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/YTDownloads"; prefEditor.PutString("rutadescarga", klk); prefEditor.Commit(); } } localizacion.Text = klk; fondo.SetImageBitmap(CreateBlurredImageoffline(this, 20, 0)); ////////////////////////////////clicks//////////////////////////// calidades.ItemSelected += (axx, ssd) => { switch (ssd.Position) { case 0: calidad = -1; break; case 1: calidad = 360; break; case 2: calidad = 720; break; } }; automatica.Click += delegate { if (automatica.Checked) { reprodautomatica = "si"; Toast.MakeText(this, "Si no hay mas elementos en cola se reproducira el primer elemento de las sugerencias", ToastLength.Long).Show(); } else { reprodautomatica = "no"; Toast.MakeText(this, "Si no hay mas elementos en cola no se ejecutara ninguna accion", ToastLength.Long).Show(); } }; toggle2.Click += delegate { if (toggle2.Checked) { new Thread(() => { if (PlaylistsHelper.HasMediaElements) { if (File.Exists(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/.gr3cache/version.gr3v")) { abrirserver = "si"; StartService(new Intent(this, typeof(serviciostreaming))); } else { AlertDialog dialogo = null; RunOnUiThread(() => { var progresox = new ProgressBar(this); progresox.Indeterminate = true; dialogo = new AlertDialog.Builder(this) .SetTitle("Buscando actualizaciones") .SetMessage("Por favor espere...") .SetCancelable(false) .SetView(progresox) .Show(); }); if (CheckInternetConnection()) { abrirserver = "si"; AlertDialog alerta = null; RunOnUiThread(() => { dialogo.Dismiss(); var progreso = new ProgressBar(this); progreso.Indeterminate = true; alerta = new AlertDialog.Builder(this) .SetTitle("Descargando archivos necesarios") .SetMessage("Por favor espere...") .SetCancelable(false) .SetView(progreso) .Show(); }); new Thread(() => { WebClient cliente = new WebClient(); var version = cliente.DownloadString("https://raw.githubusercontent.com/Gr3gorywolf/Multitube.android/master/Updates/version.gr3v"); using (var file = File.CreateText(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/.gr3cache/version.gr3v")) { file.Write(version); file.Close(); } MultitubeWebHelper.UpdateMultitubeWeb(version); RunOnUiThread(() => { alerta.Dismiss(); StartService(new Intent(this, typeof(serviciostreaming))); new AlertDialog.Builder(this) .SetTitle("Informacion") .SetMessage("El servidor de streaming le permitirara reproducir su contenido previamente descargado desde cualquier navegador de cualquier dispositivo conectado a su misma red. Puede consultar el estado de este en la barra de notificaciones") .SetPositiveButton("Entendido!", (aa, fff) => { }) .Create() .Show(); }); }).Start(); } else { RunOnUiThread(() => { dialogo.Dismiss(); Toast.MakeText(this, "Debe tener una conexion a internet para abrir el servicio por primera vez", ToastLength.Long).Show(); toggle2.Checked = false; }); } } } else { RunOnUiThread(() => { toggle2.Checked = false; Toast.MakeText(this, "Debe tener almenos 1 elemento descargado", ToastLength.Long).Show(); }); } }).Start(); } else { if (serviciostreaming.gettearinstancia() != null) { StopService(new Intent(this, typeof(serviciostreaming))); } toggle2.Checked = false; abrirserver = "no"; } }; botonclearcache.Click += delegate { AlertDialog.Builder ad = new AlertDialog.Builder(this); ad.SetCancelable(false); ad.SetTitle("Advertencia"); ad.SetIcon(Resource.Drawable.alert); ad.SetMessage("Limpiar el cache puede provocar cierta realentizacion a la hora de entrar al reproductor offline y tambien volvera a descargar los datos por lo cual necesitara internet ¿¿quiere borrar cache??"); ad.SetNegativeButton("No", no); ad.SetPositiveButton("Si", si); ad.Create(); ad.Show(); }; toggle1.Click += delegate { if (toggle1.Checked == true) { ordenalfabeto = "si"; Toast.MakeText(this, "Los elementos se organizaran alfabeticamente", ToastLength.Long).Show(); } else { ordenalfabeto = "no"; Toast.MakeText(this, "Los elementos se por fecha de descarga", ToastLength.Long).Show(); } }; botonseleccionarcarpeta.Click += async delegate { SimpleFileDialog sfd = new SimpleFileDialog(this, SimpleFileDialog.FileSelectionMode.FolderChooseRoot); klk = await sfd.GetFileOrDirectoryAsync(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath); if (probarpath(klk)) { pathvalido = true; localizacion.Text = klk; } else { Toast.MakeText(this, "Ruta invalida seleccione otra", ToastLength.Short).Show(); klk = localizacion.Text; pathvalido = false; } }; }
public Task <string> DisplayAlertAsync(string title, string message, string cancel, params string[] buttons) { var activity = (MainActivity)CrossCurrentActivity.Current.Activity; if (activity == null) { return(Task.FromResult <string>(null)); } var result = new TaskCompletionSource <string>(); var alertBuilder = new AlertDialog.Builder(activity); alertBuilder.SetTitle(title); if (!string.IsNullOrWhiteSpace(message)) { if (buttons != null && buttons.Length > 2) { if (!string.IsNullOrWhiteSpace(title)) { alertBuilder.SetTitle($"{title}: {message}"); } else { alertBuilder.SetTitle(message); } } else { alertBuilder.SetMessage(message); } } if (buttons != null) { if (buttons.Length > 2) { alertBuilder.SetItems(buttons, (sender, args) => { result.TrySetResult(buttons[args.Which]); }); } else { if (buttons.Length > 0) { alertBuilder.SetPositiveButton(buttons[0], (sender, args) => { result.TrySetResult(buttons[0]); }); } if (buttons.Length > 1) { alertBuilder.SetNeutralButton(buttons[1], (sender, args) => { result.TrySetResult(buttons[1]); }); } } } if (!string.IsNullOrWhiteSpace(cancel)) { alertBuilder.SetNegativeButton(cancel, (sender, args) => { result.TrySetResult(cancel); }); } var alert = alertBuilder.Create(); alert.CancelEvent += (o, args) => { result.TrySetResult(null); }; alert.Show(); return(result.Task); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); ActionBar.NavigationMode = ActionBarNavigationMode.Tabs; SetContentView(Resource.Layout.Main); ActionBar.Tab tabSettings = ActionBar.NewTab(); ActionBar.Tab tabCalendar = ActionBar.NewTab(); ActionBar.Tab tabSchedule = ActionBar.NewTab(); ActionBar.Tab tabEdit = ActionBar.NewTab(); tabSettings.SetText("Settings"); //tab.SetIcon(Resource.Drawable.settingssmall); tabSettings.TabSelected += (sender, args) => { SetContentView(Resource.Layout.Settings); Button btn_ok; EditText text_name; EditText text_second_name; EditText text_middle_name; EditText text_group; btn_ok = FindViewById <Button> (Resource.Id.buttonOk); text_name = FindViewById <EditText> (Resource.Id.editTextName); text_second_name = FindViewById <EditText> (Resource.Id.editTextSecondName); text_middle_name = FindViewById <EditText> (Resource.Id.editTextMiddleName); text_group = FindViewById <EditText> (Resource.Id.editTextGroup); btn_ok.Click += delegate { var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); var filePath = System.IO.Path.Combine(documentsPath, "private.txt"); System.IO.File.WriteAllText(filePath, text_name.Text + "\n" + text_second_name.Text + "\n" + text_middle_name.Text + "\n" + text_group.Text); data = new PersonalData(text_name.Text, text_second_name.Text, text_middle_name.Text, text_group.Text); stream_schedule = new List <ApiInteractionMember> (); tabSchedule.Select(); }; }; ActionBar.AddTab(tabSettings); tabCalendar.SetText("Calendar"); //tab.SetIcon(Resource.Drawable.calendarsmall); tabCalendar.TabSelected += (sender, args) => { SetContentView(Resource.Layout.Calendar); CalendarView calendar = FindViewById <CalendarView> (Resource.Id.calendarView1); calendar.DateChange += (object sender_calendar, CalendarView.DateChangeEventArgs e_calendar) => { var day_of_month = e_calendar.DayOfMonth; var current_day = DateTime.Now.Day; var month = e_calendar.Month; var current_month = DateTime.Now.Month; addedDays = day_of_month - current_day; addedMonths = month - current_month; tabSchedule.Select(); }; }; ActionBar.AddTab(tabCalendar); tabSchedule.SetText("My Schedule"); //tab.SetIcon(Resource.Drawable.thirdsmall); tabSchedule.TabSelected += (sender, args) => { data = getPersonalData(); SetContentView(Resource.Layout.Schedule); ListView listView; listView = FindViewById <ListView> (Resource.Id.listView1); DateTime current_date = DateTime.Now.AddDays(addedDays); string date = current_date.Year.ToString() + "."; if (current_date.Month.ToString().Length == 1) { date += "0" + current_date.Month.ToString() + "."; } else { date += current_date.Month.ToString() + "."; } if (current_date.Day.ToString().Length == 1) { date += "0" + current_date.Day.ToString(""); } else { date += current_date.Day.ToString(); } if (stream_schedule.Count == 0) { ApiInteraction api = new ApiInteraction(this.Assets); var full_schedule = api.GetListOfApiMembers(); foreach (var item in full_schedule) { if (item.subGroup != null && item.subGroup.Contains(data.GetGroup())) { stream_schedule.Add(item); } else if (item.stream != null && item.stream.Contains(data.GetGroup())) { stream_schedule.Add(item); } } } today_schedule_for_list = new List <string>(); today_schedule = new List <ApiInteractionMember>(); foreach (var item in stream_schedule) { if (item.date == date) { today_schedule_for_list.Add(item.beginLesson + "-" + item.endLesson + " " + item.discipline + " " + item.auditorium); today_schedule.Add(item); } } foreach (var item in added_events) { if (item.date == date) { today_schedule_for_list.Add(item.beginLesson + " " + item.discipline); today_schedule.Add(item); } } today_schedule = today_schedule.OrderBy(o => o.beginLesson).ToList(); today_schedule_for_list.Sort(); string[] items = today_schedule_for_list.ToArray(); listView.Adapter = new ArrayAdapter <String>(this, Android.Resource.Layout.SimpleListItem1, items); listView.ItemClick += (object senderlist, ListView.ItemClickEventArgs e_list) => { string message = ""; if (today_schedule[e_list.Position].auditorium != null) { message += "Auditorium: " + today_schedule[e_list.Position].auditorium; } if (today_schedule[e_list.Position].beginLesson != null) { message += "\n\nBegin Lesson: " + today_schedule[e_list.Position].beginLesson; } if (today_schedule[e_list.Position].endLesson != null) { message += "\n\nEnd Lesson: " + today_schedule[e_list.Position].endLesson; } if (today_schedule[e_list.Position].discipline != null) { message += "\n\nDiscipline: " + today_schedule[e_list.Position].discipline; } if (today_schedule[e_list.Position].lecturer != null) { message += "\n\nLecturer: " + today_schedule[e_list.Position].lecturer; } if (today_schedule[e_list.Position].kindOfWork != null) { message += "\n\nKind Of Work: " + today_schedule[e_list.Position].kindOfWork; } if (today_schedule[e_list.Position].building != null) { message += "\n\nBuilding: " + today_schedule[e_list.Position].building; } if (today_schedule[e_list.Position].dayOfWeekString != null) { message += "\n\nDay Of Week: " + today_schedule[e_list.Position].dayOfWeekString; } if (today_schedule[e_list.Position].group != null) { message += "\n\nGroup: " + today_schedule[e_list.Position].group; } if (today_schedule[e_list.Position].subGroup != null) { message += "\n\nSubgroup: " + today_schedule[e_list.Position].subGroup; } if (today_schedule[e_list.Position].stream != null) { message += "\n\nStream: " + today_schedule[e_list.Position].stream; } AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.SetTitle("Schedule"); builder.SetMessage(message); builder.SetPositiveButton("Ok", (sender1, args1) => { builder.Dispose(); }); builder.SetNegativeButton("Delete this item", (sender1, args1) => { int index = e_list.Position; //today_schedule.RemoveAt(index); var item_need_to_delete = today_schedule[index]; bool isFound = false; int i = 0; while (!isFound && i < added_events.Count) { if ((added_events[i].discipline == item_need_to_delete.discipline) && (added_events[i].beginLesson == item_need_to_delete.beginLesson) && (added_events[i].date == item_need_to_delete.date)) { added_events.RemoveAt(i); isFound = true; } else { i++; } } i = 0; isFound = false; while (!isFound && i < stream_schedule.Count) { if ((stream_schedule[i].discipline == item_need_to_delete.discipline) && (stream_schedule[i].beginLesson == item_need_to_delete.beginLesson) && (stream_schedule[i].endLesson == item_need_to_delete.endLesson) && (stream_schedule[i].date == item_need_to_delete.date)) { stream_schedule.RemoveAt(i); isFound = true; } else { i++; } } tabSettings.Select(); tabSchedule.Select(); }); builder.Show(); }; TextView textCurrentDay = FindViewById <TextView> (Resource.Id.textViewDate); ImageButton btn_prev; ImageButton btn_second; textCurrentDay.Text = DateTime.Now.AddDays(addedDays).ToString("yyyy-M-d dddd"); btn_prev = FindViewById <ImageButton> (Resource.Id.imageButtonPrev); btn_second = FindViewById <ImageButton> (Resource.Id.imageButtonSecond); btn_prev.Click += delegate { addedDays -= 1; tabSettings.Select(); tabSchedule.Select(); }; btn_second.Click += delegate { addedDays += 1; tabSettings.Select(); tabSchedule.Select(); }; }; ActionBar.AddTab(tabSchedule); tabEdit.SetText("Edit Schedule"); //tab.SetIcon(Resource.Drawable.editsmall); tabEdit.TabSelected += (sender, args) => { SetContentView(Resource.Layout.Edit); Button btn_ok_add = FindViewById <Button> (Resource.Id.buttonOkAdd); EditText edit_text_add = FindViewById <EditText> (Resource.Id.editTextAdd); TimePicker time_picker = FindViewById <TimePicker> (Resource.Id.timePicker1); time_picker.SetIs24HourView(Java.Lang.Boolean.True); btn_ok_add.Click += delegate { var hour = time_picker.CurrentHour; var minutes = time_picker.CurrentMinute; var text = edit_text_add.Text; string time = ""; if (hour.ToString().Length == 1) { time += "0" + hour.ToString(); } else { time += hour.ToString(); } time += ":"; if (minutes.ToString().Length == 1) { time += "0" + minutes.ToString(); } else { time += minutes.ToString(); } DateTime current_date = DateTime.Now.AddDays(addedDays); string date = current_date.Year.ToString() + "."; if (current_date.Month.ToString().Length == 1) { date += "0" + current_date.Month.ToString() + "."; } else { date += current_date.Month.ToString() + "."; } if (current_date.Day.ToString().Length == 1) { date += "0" + current_date.Day.ToString(""); } else { date += current_date.Day.ToString(); } added_events.Add(new ApiInteractionMember("null", 0, time, "null", date, "null", 0, "null", text, "null", "null", 0, "null", "null", 0, "null", 0, "null", 0)); tabSchedule.Select(); }; }; ActionBar.AddTab(tabEdit); // This event fires when the ServiceConnection lets the client (our App class) know that // the Service is connected. We use this event to start updating the UI with location // updates from the Service App.Current.LocationServiceConnected += (object sender, ServiceConnectedEventArgs e) => { //Log.Debug (logTag, "ServiceConnected Event Raised"); // notifies us of location changes from the system App.Current.LocationService.LocationChanged += HandleLocationChanged; //notifies us of user changes to the location provider (ie the user disables or enables GPS) App.Current.LocationService.ProviderDisabled += HandleProviderDisabled; App.Current.LocationService.ProviderEnabled += HandleProviderEnabled; // notifies us of the changing status of a provider (ie GPS no longer available) App.Current.LocationService.StatusChanged += HandleStatusChanged; }; // Start the location service: App.StartLocationService(); }
public void OnSensorChanged(SensorEvent e) { if (e.Sensor.Type == SensorType.Accelerometer) { _accelerometer_textview_x.Text = string.Format("x={0:f}", e.Values[0]); _accelerometer_textview_y.Text = string.Format("y={0:f}", e.Values[1]); _accelerometer_textview_z.Text = string.Format("z={0:f}", e.Values[2]); _accelerometer_X.Progress = (int)((e.Values[0]) * 10); _accelerometer_Y.Progress = (int)((e.Values[1]) * 10); _accelerometer_Z.Progress = (int)((e.Values[2]) * 10); _accelerometer_X_reverse.Progress = (int)((10 + e.Values[0]) * 10); _accelerometer_Y_reverse.Progress = (int)((10 + e.Values[1]) * 10); _accelerometer_Z_reverse.Progress = (int)((10 + e.Values[2]) * 10); } if (e.Sensor.Type == SensorType.Proximity) { if (e.Values[0] == 0 && !alert_created) { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Proximity senzor"); alert.SetMessage("Nieco je pred senzorom"); alert.SetNeutralButton("OK", (senderAlert, args) => { alert_created = false; }); Dialog dialog = alert.Create(); dialog.Show(); alert_created = true; } } if (e.Sensor.Type == SensorType.Light) { if (e.Values[0] < 400 || e.Values[0] > 14000) { _light_textview.SetTextColor(Android.Graphics.Color.Red); _light_textview.Text = string.Format("{0:d} lux", (int)e.Values[0]); if (!vibrating) { vibrating = true; //vibrator.Vibrate(500); } } else { vibrating = false; _light_textview.SetTextColor(Android.Graphics.Color.White); _light_textview.Text = string.Format("{0:d} lux", (int)e.Values[0]); } float to_Angle = 0.012F * e.Values[0] - 90; RotateAnimation rAnim = new RotateAnimation(from_angle, to_Angle, Dimension.RelativeToSelf, 0.5F, Dimension.RelativeToSelf, 0.5F); rAnim.Interpolator = new LinearInterpolator(); rAnim.RepeatCount = Animation.Infinite; rAnim.Duration = 100; _image_strelka.StartAnimation(rAnim); from_angle = to_Angle; } }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); EditText userid = FindViewById <EditText>(Resource.Id.EditText_userID); EditText password = FindViewById <EditText>(Resource.Id.EditText_Password); EditText location = FindViewById <EditText>(Resource.Id.EditText_Location); EditText date = FindViewById <EditText>(Resource.Id.EditText_Date); EditText time = FindViewById <EditText>(Resource.Id.EditText_Time); Button button = FindViewById <Button>(Resource.Id.Button_setavail); Button button2 = FindViewById <Button>(Resource.Id.Button_setnotavail); Button button3 = FindViewById <Button>(Resource.Id.Button_getstatus); Button btnGoToTracking = FindViewById <Button>(Resource.Id.btnGoToTracking); TMSNextLevel.webrefMStrongCreates.WebService client = new TMSNextLevel.webrefMStrongCreates.WebService(); userid.Text = prefs.GetString("strUserID", null); password.Text = prefs.GetString("strPassword", null); btnGoToTracking.Click += delegate { StartActivity(new Intent(this.ApplicationContext, typeof(Secondary))); Finish(); }; button.Click += delegate // set driver avail { ISharedPreferencesEditor editor = prefs.Edit(); editor.PutString("strUserID", userid.Text); editor.PutString("strPassword", password.Text); editor.Apply(); ProgressDialog progressDialog = ProgressDialog.Show(this, "Loading...", "checking account info...", true); var dialogRunning = 1; Task.Run(() => { Thread.Sleep(20000); if (dialogRunning == 1) { RunOnUiThread(() => { AlertDialog.Builder ad = new AlertDialog.Builder(this); ad.SetTitle("Failed"); ad.SetMessage("Operation Timed Out. Service Unreachable."); ad.Show(); progressDialog.Dismiss(); }); } }); Task.Run(() => { var result = client.SetDriverAvail(userid.Text, password.Text, location.Text, date.Text + time.Text); RunOnUiThread(() => { if (result == 1) { AlertDialog.Builder ad = new AlertDialog.Builder(this); ad.SetTitle("Success"); ad.SetMessage("You are now set to Available."); ad.Show(); dialogRunning = 0; } else { AlertDialog.Builder ad = new AlertDialog.Builder(this); ad.SetTitle("Failed"); ad.SetMessage("Please check your login credentials. Location, Date, and Time are required."); ad.Show(); dialogRunning = 0; } progressDialog.Dismiss(); }); }); }; button2.Click += delegate { ISharedPreferencesEditor editor = prefs.Edit(); editor.PutString("strUserID", userid.Text); editor.PutString("strPassword", password.Text); editor.Apply(); ProgressDialog progressDialog = ProgressDialog.Show(this, "Loading...", "checking account info...", true); var dialogRunning = 1; Task.Run(() => { Thread.Sleep(20000); if (dialogRunning == 1) { RunOnUiThread(() => { AlertDialog.Builder ad = new AlertDialog.Builder(this); ad.SetTitle("Failed"); ad.SetMessage("Operation Timed Out. Service Unreachable."); ad.Show(); progressDialog.Dismiss(); }); } }); Task.Run(() => { var result = client.SetDriverNotAvail(userid.Text, password.Text); RunOnUiThread(() => { if (result == 1) { AlertDialog.Builder ad = new AlertDialog.Builder(this); ad.SetTitle("Success"); ad.SetMessage("You are now set to NOT available."); ad.Show(); dialogRunning = 0; } else { AlertDialog.Builder ad = new AlertDialog.Builder(this); ad.SetTitle("Failed"); ad.SetMessage("Please check your login credentials."); ad.Show(); dialogRunning = 0; } progressDialog.Dismiss(); }); }); }; button3.Click += delegate // GET STATUS { ISharedPreferencesEditor editor = prefs.Edit(); editor.PutString("strUserID", userid.Text); editor.PutString("strPassword", password.Text); editor.Apply(); ProgressDialog progressDialog = ProgressDialog.Show(this, "Loading...", "checking account info...", true); var dialogRunning = 1; Task.Run(() => // RUN TIMEOUT CHECKER { Thread.Sleep(20000); if (dialogRunning == 1) { RunOnUiThread(() => { AlertDialog.Builder ad = new AlertDialog.Builder(this); ad.SetTitle("Failed"); ad.SetMessage("Operation Timed Out. Service Unreachable."); ad.Show(); progressDialog.Dismiss(); }); } }); Task.Run(() => // RUN WebService call in Thread, once returned display Dialog { var result = client.GetStatus(userid.Text, password.Text); RunOnUiThread(() => { AlertDialog.Builder ad = new AlertDialog.Builder(this); ad.SetTitle("TMS Next Level"); ad.SetMessage(result); ad.Show(); progressDialog.Dismiss(); dialogRunning = 0; }); }); }; date.Click += (sender, e) => { DateTime today = DateTime.Today; DatePickerDialog dialog = new DatePickerDialog(this, OnDateSet, today.Year, today.Month - 1, today.Day); dialog.Show(); }; void OnDateSet(object sender, DatePickerDialog.DateSetEventArgs e) { string varTime = e.Date.ToString(); varTime = varTime.Remove(varTime.Length - 11); date.Text = varTime; } time.Click += (sender, e) => { DateTime today = DateTime.Today; TimePickerDialog dialog = new TimePickerDialog(this, OnDateSet2, today.Hour, today.Minute, false); dialog.Show(); }; void OnDateSet2(object sender, TimePickerDialog.TimeSetEventArgs e) { string hours = e.HourOfDay.ToString(); if (e.HourOfDay < 10) { hours = "0" + e.HourOfDay; } if (e.Minute < 10) { time.Text = hours + ":0" + e.Minute; } else { time.Text = hours + ":" + e.Minute; } } }
private void ForgotOnClick(object sender, EventArgs eventArgs) { /* * var alert = new AlertDialog.Builder(this); * alert.SetTitle("Oh ne!"); * alert.SetPositiveButton("U redu", (o, args) => { alert.Dispose(); }); * * alert.SetMessage("Nista ne brinite!\n\nRadi resetovanja sifre, javite se nasem adminu na mail:\n\[email protected]"); * * alert.Show(); */ var inflater = LayoutInflater.From(this); var view = inflater.Inflate(Resource.Layout.forgotDialog, null); var dialogForgot = new AlertDialog.Builder(this); var dialogPin = new AlertDialog.Builder(this); var alertUspesno = new AlertDialog.Builder(this); var username = view.FindViewById <TextView>(Resource.Id.forgotUsername); string ime = ""; dialogForgot.SetView(view); dialogForgot.SetPositiveButton("Resetuj", delegate(object o, DialogClickEventArgs args) { if (!username.Text.Equals(String.Empty)) { ime = username.Text; try { //Api.Api.ZaboravljenaSifra(ime); dialogForgot.Dispose(); var alert = new AlertDialog.Builder(this); alert.SetTitle("Resetovanje!"); alert.SetMessage("Proverite Vas mail kako bi ste dobili PIN za reset.\n" + "Pin ukucajte na sledecoj formi."); alert.SetPositiveButton("U redu", (ooo, argsss) => { alert.Dispose(); dialogPin.Show(); }); alert.Show(); } catch (Exception ex) { Toast.MakeText(this, ex.Message, ToastLength.Long).Show(); dialogForgot.Dispose(); } } else { Toast.MakeText(this, "Unesite korisnicko ime!", ToastLength.Short).Show(); } }); dialogForgot.SetNegativeButton("Unesi PIN", delegate(object o, DialogClickEventArgs args) { dialogForgot.Dispose(); dialogPin.Show(); }); var view2 = inflater.Inflate(Resource.Layout.pinDialog, null); dialogPin.SetView(view2); dialogPin.SetPositiveButton("Potvrdi", delegate(object o, DialogClickEventArgs args) { var pin = view2.FindViewById <TextView>(Resource.Id.pin); var sifra = view2.FindViewById <TextView>(Resource.Id.pinNovaSifra); var sifraOpet = view2.FindViewById <TextView>(Resource.Id.pinNovaSifraOpet); if (sifra.Text.Equals(sifraOpet.Text) && !pin.Text.Equals(String.Empty)) { PassRecoveryDto noviPass = new PassRecoveryDto() { Pin = pin.Text, KorisnickoIme = ime, NovaSifra = sifra.Text }; try { // Api.Api.OporavakSifre(noviPass); } catch (Exception ex) { Toast.MakeText(this, ex.Message, ToastLength.Long).Show(); dialogPin.Dispose(); } } else { if (!pin.Text.Equals(String.Empty)) { Toast.MakeText(this, "Unesite PIN!", ToastLength.Short).Show(); } else { Toast.MakeText(this, "Sifre se ne poklapaju!", ToastLength.Short).Show(); } } }); alertUspesno.SetTitle("Obavestenje!"); alertUspesno.SetMessage("Uspesno ste resetovali Vasu sifru!"); alertUspesno.SetPositiveButton("U redu", (o, args) => alertUspesno.Dispose()); dialogForgot.Show(); }
public void enemyMove() { etimer = new System.Timers.Timer(); etimer.Interval = 24 - (level * 4); etimer.Elapsed += (sender, e) => { RunOnUiThread(() => { ImageView enemy = FindViewById <ImageView>(Resource.Id.mini); ImageView rocket = FindViewById <ImageView>(Resource.Id.rocket); var metrics = Resources.DisplayMetrics; int width = metrics.WidthPixels - enemy.Width; int height = metrics.HeightPixels - (enemy.Width * 2); if (bx > width) { dx = -1; } if (bx < 20) { dx = 1; } if (by > height) { dy = -1; } if (by < 0) { dy = 1; } if ((rocket.GetY() + (rocket.Height / 2) <= by + enemy.Height || (rocket.GetY() + (rocket.Height / 2) <= by) && by >= rocket.GetY()) && rocket.GetX() + rocket.Width >= bx) { ProgressBar userLife = FindViewById <ProgressBar>(Resource.Id.user_life); userLife.Progress -= 20; rocket.Alpha = 0; rocket.Animate() .SetDuration(5000) .Alpha(10); MediaPlayer player1; player1 = MediaPlayer.Create(this, Resource.Raw.blast); player1.Start(); player1.SetVolume(SoundSetup.sound_level, SoundSetup.sound_level); by = 0; bx = width; if (userLife.Progress == 0) { etimer.Close(); AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Game Over"); alert.SetMessage("Unfortunately enemy has hit your rocket."); alert.SetPositiveButton("Continue", (senderAlert, args) => { Intent activity2 = new Intent(this, typeof(GameOver)); string score = FindViewById <TextView>(Resource.Id.score).Text; activity2.PutExtra("score", score); this.StartActivity(activity2); this.Finish(); }); alert.Show(); } } bx = bx + dx; enemy.SetX(bx); by = by + dy; enemy.SetY(by); }); }; etimer.Enabled = true; }
private static AlertDialogInfo CreateDialog( string content, string title, string okText = null, string cancelText = null, Action <bool> afterHideCallbackWithResponse = null) { var tcs = new TaskCompletionSource <bool>(); var builder = new AlertDialog.Builder(ActivityBase.CurrentActivity); builder.SetMessage(content); builder.SetTitle(title); AlertDialog dialog = null; builder.SetPositiveButton( okText ?? "OK", (d, index) => { tcs.TrySetResult(true); // ReSharper disable AccessToModifiedClosure if (dialog != null) { dialog.Dismiss(); dialog.Dispose(); } if (afterHideCallbackWithResponse != null) { afterHideCallbackWithResponse(true); } // ReSharper restore AccessToModifiedClosure }); if (cancelText != null) { builder.SetNegativeButton( cancelText, (d, index) => { tcs.TrySetResult(false); // ReSharper disable AccessToModifiedClosure if (dialog != null) { dialog.Dismiss(); dialog.Dispose(); } if (afterHideCallbackWithResponse != null) { afterHideCallbackWithResponse(false); } // ReSharper restore AccessToModifiedClosure }); } builder.SetOnDismissListener( new OnDismissListener( () => { tcs.TrySetResult(false); if (afterHideCallbackWithResponse != null) { afterHideCallbackWithResponse(false); } })); dialog = builder.Create(); return(new AlertDialogInfo { Dialog = dialog, Tcs = tcs }); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); var FooterText = FindViewById <TextView>(Resource.Id.footerText); string version = PackageManager.GetPackageInfo(PackageName, 0).VersionName; FooterText.Text = $"InstaShit.Android v{version} - Created by Konrad Krawiec"; StatusText = FindViewById <TextView>(Resource.Id.statusTextView); StartButton = FindViewById <Button>(Resource.Id.startButton); ProgressBar = FindViewById <ProgressBar>(Resource.Id.progressBar); AnswerCountText = FindViewById <TextView>(Resource.Id.answerCountText); LogButton = FindViewById <Button>(Resource.Id.logButton); SettingsButton = FindViewById <Button>(Resource.Id.settingsButton); _receiver = new Receiver(); _receiver.Activity = this; if (savedInstanceState != null) { StatusText.Text = savedInstanceState.GetString("statusText", "Status: Stopped"); } if (StatusText.Text == "Status: Stopped") { StartButton.Text = "Start InstaShit"; StartButton.Enabled = true; ProgressBar.Indeterminate = false; ProgressBar.Progress = 0; } else if (StatusText.Text == "Status: Running") { StartButton.Text = "Stop InstaShit"; StartButton.Enabled = true; ProgressBar.Indeterminate = true; SettingsButton.Enabled = false; AnswerCountText.Visibility = Android.Views.ViewStates.Visible; } else if (StatusText.Text == "Status: Stopping") { StartButton.Text = "Stopping..."; StartButton.Enabled = false; SettingsButton.Enabled = false; ProgressBar.Indeterminate = true; AnswerCountText.Visibility = Android.Views.ViewStates.Visible; } else if (StatusText.Text == "Status: Finished") { StartButton.Text = "Start InstaShit"; StartButton.Enabled = true; StatusText.Text = "Status: Stopped"; ProgressBar.Indeterminate = false; ProgressBar.Progress = 100; } AnswerCountText.Text = "Answered questions: " + Counter; LogButton.Click += (sender, e) => { var intent = new Intent(this, typeof(LogActivity)); intent.PutStringArrayListExtra("log", Log); StartActivity(intent); }; SettingsButton.Click += (sender, e) => { var intent = new Intent(this, typeof(SettingsActivity)); StartActivity(intent); }; StartButton.Click += (sender, e) => { if (StartButton.Text == "Start InstaShit") { Log.Clear(); if (!File.Exists(GetFileLocation("settings.json"))) { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("Error"); alertBuilder.SetMessage("The settings file doesn't exist. Do you want to create it now?"); alertBuilder.SetPositiveButton("Yes", (senderAlert, args) => { var intent = new Intent(this, typeof(SettingsActivity)); StartActivity(intent); }); alertBuilder.SetNegativeButton("No", (senderAlert, args) => { }); var dialog = alertBuilder.Create(); dialog.Show(); Log.Add("Can't find settings file!"); return; } InstaShitService.ShouldContinue = true; StartButton.Text = "Stop InstaShit"; StatusText.Text = "Status: Running"; SettingsButton.Enabled = false; ProgressBar.Indeterminate = true; Intent instaShitIntent = new Intent(this, typeof(InstaShitService)); Counter = 0; AnswerCountText.Text = "Answered questions: " + Counter; AnswerCountText.Visibility = Android.Views.ViewStates.Visible; StartService(instaShitIntent); } else { InstaShitService.ShouldContinue = false; StatusText.Text = "Status: Stopping"; StartButton.Text = "Stopping..."; StartButton.Enabled = false; } }; LocalBroadcastManager.GetInstance(this).RegisterReceiver(_receiver, new IntentFilter("com.InstaShit.Android.INFORMATION")); }
private static AlertDialogInfo CreateDialog(string content, string title, string okText = null, string cancelText = null, Action<bool> afterHideCallbackWithResponse = null) { var tcs = new TaskCompletionSource<bool>(); var builder = new AlertDialog.Builder(AppCompatActivityBase.CurrentActivity); builder.SetMessage(content); builder.SetTitle(title); var dialog = (AlertDialog)null; builder.SetPositiveButton(okText ?? "OK", (d, index) => { tcs.TrySetResult(true); if (dialog != null) { dialog.Dismiss(); dialog.Dispose(); } if (afterHideCallbackWithResponse == null) return; afterHideCallbackWithResponse(true); }); if (cancelText != null) { builder.SetNegativeButton(cancelText, (d, index) => { tcs.TrySetResult(false); if (dialog != null) { dialog.Dismiss(); dialog.Dispose(); } if (afterHideCallbackWithResponse == null) return; afterHideCallbackWithResponse(false); }); } builder.SetOnDismissListener(new OnDismissListener(() => { tcs.TrySetResult(false); if (afterHideCallbackWithResponse == null) return; afterHideCallbackWithResponse(false); })); dialog = builder.Create(); return new AlertDialogInfo { Dialog = dialog, Tcs = tcs }; }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); ConnectivityManager connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService); NetworkInfo activeConnection = connectivityManager.ActiveNetworkInfo; bool isOnline = (activeConnection != null) && activeConnection.IsConnected; if (!isOnline) { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("No network access!"); alert.SetMessage("Can't connect to server. No network access."); alert.SetPositiveButton("OK", (senderAlert, args) => { Finish(); }); Dialog dialog = alert.Create(); dialog.Show(); } else { SetContentView(Resource.Layout.Main); Log.Debug("Start", "Started"); LoadValues(); if (string.IsNullOrEmpty(UserAc)) { StartActivity(typeof(LoginActivity)); Finish(); } else { ImageButton sendbutton = FindViewById <ImageButton>(Resource.Id.imageButtonSend); ImageButton smilebutton = FindViewById <ImageButton>(Resource.Id.imgButtonSmile); edit = FindViewById <EditText>(Resource.Id.editTextMessage); chatlay = FindViewById <LinearLayout>(Resource.Id.linearLayoutchat); scrollview = FindViewById <ScrollView>(Resource.Id.scrollviewchat); onlineimg = FindViewById <ImageView>(Resource.Id.imageViewStatus); onlinetxt = FindViewById <TextView>(Resource.Id.textViewStatus); sendbutton.Click += delegate { SendMessage(null); }; smilebutton.Click += delegate { Log.Debug("Smile Activity", "Smile Activity started"); StartActivity(typeof(SmileActivity)); }; System.Threading.Timer timer = new System.Threading.Timer((e) => { if (ScrollDown) { RunOnUiThread(() => { scrollview.FullScroll(FocusSearchDirection.Down); ScrollDown = false; }); } if (Smile) { RunOnUiThread(() => { Smile = false; message.SendMessage(connection.GetXmppIm(), ReceiverJID, SmileCode); ImageView img = new ImageView(this); img.SetImageDrawable(SmileActivity.GetSmileImage(this, SmileCodeIM)); img.LayoutParameters = new ViewGroup.LayoutParams(LayoutParams.WrapContent, LayoutParams.WrapContent); chatlay.AddView(img); ScrollDown = true; }); } }, null, 500, 200); System.Threading.Timer timerstatus = new System.Threading.Timer((e) => { connection.SetONIM(true); }, null, 5000, 15000); string usr = "******" + UserAc; if (Administrator) { ReceiverJID = usr + "@" + XmppConnection.Server; usr = "******" + usr; } else { ReceiverJID = "Admin_" + usr + "@" + XmppConnection.Server; } vibrator = (Vibrator)GetSystemService(VibratorService); connection.ConnectToXMPPIM(usr, PasswordAc); Log.Debug("XMPP", "Connected as " + connection.GetXmppIm().Jid); connection.GetXmppIm().Message += Connection_Message; connection.AddToRoster(ReceiverJID); connection.GetXmppIm().RequestSubscription(ReceiverJID); connection.ApproveRequest(ReceiverJID); connection.GetXmppIm().Status += Connection_Status; } } }
public void OnClick(object sender, EventArgs e) { HideKeyboard(); var model = blankPicker; var picker = new NumberPicker(Context); if (model.Items != null && model.Items.Any()) { picker.MaxValue = model.Items.Count - 1; picker.MinValue = 0; picker.SetDisplayedValues(model.Items.ToArray()); picker.WrapSelectorWheel = false; picker.DescendantFocusability = DescendantFocusability.BlockDescendants; picker.Value = model.SelectedIndex; } var layout = new LinearLayout(Context) { Orientation = Orientation.Vertical }; layout.AddView(picker); var builder = new AlertDialog.Builder(Context); builder.SetView(layout); builder.SetTitle(model.Title ?? ""); builder.SetNegativeButton(blankPicker.CancelButtonText ?? "Cancel", (s, a) => { blankPicker.SendCancelClicked(); EController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); _dialog = null; Control.ClearFocus(); HideKeyboard(); }); builder.SetPositiveButton(blankPicker.DoneButtonText ?? "OK", (s, a) => { EController.SetValueFromRenderer(BlankPicker.SelectedIndexProperty, picker.Value); //blankPicker.SelectedItem = picker.Value; blankPicker.SendDoneClicked(); // 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 (blankPicker != null) { if (model.Items.Count > 0 && blankPicker.SelectedIndex >= 0) { Control.Text = model.Items[blankPicker.SelectedIndex]; } EController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); Control.ClearFocus(); HideKeyboard(); } _dialog = null; }); _dialog = builder.Create(); _dialog.DismissEvent += (s, args) => { EController?.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); Control.ClearFocus(); HideKeyboard(); }; _dialog.Show(); }
public View GetSampleContent(Context con) { context = con; InitialMethod(); ScrollView scroll = new ScrollView(con); bool isTablet = SfMaskedEditText.IsTabletDevice(con); linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(12, 12, 12, 12); TextView headLabel = new TextView(con); headLabel.TextSize = 30; headLabel.SetTextColor(Color.ParseColor("#262626")); headLabel.Typeface = Typeface.DefaultBold; headLabel.Text = "Funds Transfer"; linear.AddView(headLabel); TextView fundTransferLabelSpacing = new TextView(con); fundTransferLabelSpacing.SetHeight(40); linear.AddView(fundTransferLabelSpacing); TextView textToAccount = new TextView(con); textToAccount.SetTextColor(Color.ParseColor("#6d6d72")); textToAccount.TextSize = 18; textToAccount.Typeface = Typeface.Default; textToAccount.Text = "To Account"; textToAccount.SetPadding(0, 0, 0, 10); linear.AddView(textToAccount); sfToAccount = new SfMaskedEdit(con); sfToAccount.Mask = "0000 0000 0000 0000"; sfToAccount.Gravity = GravityFlags.Start; sfToAccount.ValidationMode = InputValidationMode.KeyPress; sfToAccount.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; sfToAccount.Hint = "1234 1234 1234 1234"; sfToAccount.FocusChange += SfToAccount_FocusChange; sfToAccount.SetHintTextColor(Color.LightGray); linear.AddView(sfToAccount); erroToAccount = new TextView(con); erroToAccount.SetTextColor(Color.Red); erroToAccount.TextSize = 14; erroToAccount.Typeface = Typeface.Default; linear.AddView(erroToAccount); TextView textDesc = new TextView(con); textDesc.Text = "Description"; textDesc.Typeface = Typeface.Default; textDesc.SetPadding(0, 30, 0, 10); textDesc.TextSize = 18; linear.AddView(textDesc); sfDesc = new SfMaskedEdit(con); sfDesc.Mask = ""; sfDesc.Gravity = GravityFlags.Start; sfDesc.ValidationMode = InputValidationMode.KeyPress; sfDesc.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; sfDesc.Hint = "Enter description"; sfDesc.FocusChange += SfToAccount_FocusChange; sfDesc.SetHintTextColor(Color.LightGray); linear.AddView(sfDesc); TextView textAmount = new TextView(con); textAmount.Text = "Amount"; textAmount.Typeface = Typeface.Default; textAmount.SetPadding(0, 30, 0, 10); textAmount.TextSize = 18; linear.AddView(textAmount); amountMask = new SfMaskedEdit(con); amountMask.Mask = "$ 0,000.00"; amountMask.Gravity = GravityFlags.Start; amountMask.ValidationMode = InputValidationMode.KeyPress; amountMask.ValueMaskFormat = MaskFormat.IncludePromptAndLiterals; amountMask.Hint = "$ 3,874.00"; amountMask.FocusChange += SfToAccount_FocusChange; amountMask.SetHintTextColor(Color.LightGray); linear.AddView(amountMask); errotextAmount = new TextView(con); errotextAmount.SetTextColor(Color.Red); errotextAmount.TextSize = 12; errotextAmount.Typeface = Typeface.Default; linear.AddView(errotextAmount); TextView textEmail = new TextView(con); textEmail.Text = "Email ID"; textEmail.Typeface = Typeface.Default; textEmail.SetPadding(0, 30, 0, 10); textEmail.TextSize = 18; linear.AddView(textEmail); emailMask = new SfMaskedEdit(con); emailMask.Mask = @"\w+@\w+\.\w+"; emailMask.MaskType = MaskType.RegEx; emailMask.Gravity = GravityFlags.Start; emailMask.ValidationMode = InputValidationMode.KeyPress; emailMask.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; emailMask.Hint = "*****@*****.**"; emailMask.FocusChange += SfToAccount_FocusChange; emailMask.SetHintTextColor(Color.LightGray); linear.AddView(emailMask); errotextEmail = new TextView(con); errotextEmail.SetTextColor(Color.Red); errotextEmail.TextSize = 12; errotextEmail.Typeface = Typeface.Default; linear.AddView(errotextEmail); TextView textPhone = new TextView(con); textPhone.Text = "Mobile Number "; textPhone.Typeface = Typeface.Default; textPhone.SetPadding(0, 30, 0, 10); textPhone.TextSize = 18; linear.AddView(textPhone); phoneMask = new SfMaskedEdit(con); phoneMask.Mask = "+1 000 000 0000"; phoneMask.Gravity = GravityFlags.Start; phoneMask.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; phoneMask.ValidationMode = InputValidationMode.KeyPress; phoneMask.Hint = "+1 323 339 3392"; phoneMask.FocusChange += SfToAccount_FocusChange; phoneMask.SetHintTextColor(Color.LightGray); linear.AddView(phoneMask); errotextPhone = new TextView(con); errotextPhone.SetTextColor(Color.Red); errotextPhone.TextSize = 12; errotextPhone.Typeface = Typeface.Default; linear.AddView(errotextPhone); TextView transferButtonSpacing = new TextView(con); transferButtonSpacing.SetHeight(30); Button transferButton = new Button(con); transferButton.SetWidth(ActionBar.LayoutParams.MatchParent); transferButton.SetHeight(40); transferButton.Text = "TRANSFER MONEY"; transferButton.SetTextColor(Color.White); transferButton.SetBackgroundColor(Color.Rgb(72, 178, 224)); transferButton.Click += (object sender, EventArgs e) => { if (string.IsNullOrEmpty(sfToAccount.Text) || string.IsNullOrEmpty(sfDesc.Text) || string.IsNullOrEmpty(amountMask.Text) || string.IsNullOrEmpty(emailMask.Text) || string.IsNullOrEmpty(phoneMask.Text)) { resultsDialog.SetMessage("Please fill all the required data!"); } else if ((sfToAccount.HasError || sfDesc.HasError || amountMask.HasError || emailMask.HasError || phoneMask.HasError)) { resultsDialog.SetMessage("Please enter valid details"); } else { resultsDialog.SetMessage(string.Format("Amount of {0} has been transferred successfully!", amountMask.Value)); sfToAccount.Value = string.Empty; sfDesc.Value = string.Empty; amountMask.Value = string.Empty; emailMask.Value = string.Empty; phoneMask.Value = string.Empty; } resultsDialog.Create().Show(); }; linear.AddView(transferButtonSpacing); linear.AddView(transferButton); TextView transferAfterButtonSpacing = new TextView(con); transferAfterButtonSpacing.SetHeight(60); linear.AddView(transferAfterButtonSpacing); sfToAccount.ValueChanged += SfToAccount_ValueChanged; sfToAccount.MaskInputRejected += SfToAccount_MaskInputRejected; amountMask.ValueChanged += AmountMask_ValueChanged; amountMask.MaskInputRejected += AmountMask_MaskInputRejected; emailMask.ValueChanged += EmailMask_ValueChanged; emailMask.MaskInputRejected += EmailMask_MaskInputRejected; phoneMask.ValueChanged += PhoneMask_ValueChanged; phoneMask.MaskInputRejected += PhoneMask_MaskInputRejected; linear.Touch += (object sender, View.TouchEventArgs e) => { if (sfToAccount.IsFocused || sfDesc.IsFocused || amountMask.IsFocused || emailMask.IsFocused || phoneMask.IsFocused) { Rect outRect = new Rect(); sfToAccount.GetGlobalVisibleRect(outRect); sfDesc.GetGlobalVisibleRect(outRect); amountMask.GetGlobalVisibleRect(outRect); emailMask.GetGlobalVisibleRect(outRect); phoneMask.GetGlobalVisibleRect(outRect); if (!outRect.Contains((int)e.Event.RawX, (int)e.Event.RawY)) { sfToAccount.ClearFocus(); sfDesc.ClearFocus(); amountMask.ClearFocus(); emailMask.ClearFocus(); phoneMask.ClearFocus(); } } hideSoftKeyboard((Activity)con); }; //results dialog resultsDialog = new AlertDialog.Builder(con); resultsDialog.SetTitle("Status"); resultsDialog.SetPositiveButton("OK", (object sender, DialogClickEventArgs e) => { }); resultsDialog.SetCancelable(true); frame.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); frame.SetBackgroundColor(Color.White); frame.SetPadding(10, 10, 10, 10); //scrollView1 mainPageScrollView = new ScrollView(con); mainPageScrollView.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.7), GravityFlags.Top | GravityFlags.CenterHorizontal); mainPageScrollView.AddView(linear); frame.AddView(mainPageScrollView); //buttomButtonLayout buttomButtonLayout = new FrameLayout(con); buttomButtonLayout.SetBackgroundColor(Color.Transparent); buttomButtonLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.1), GravityFlags.Bottom | GravityFlags.CenterHorizontal); //propertyButton propertyButton = new Button(con); propertyButton.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent, GravityFlags.Bottom | GravityFlags.CenterHorizontal); propertyButton.Text = "OPTIONS"; propertyButton.Gravity = GravityFlags.Start; propertyFrameLayout = new FrameLayout(con); propertyFrameLayout.SetBackgroundColor(Color.Rgb(236, 236, 236)); propertyFrameLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.3), GravityFlags.CenterHorizontal); propertyFrameLayout.AddView(GetPropertyLayout(con)); //propertyButton Click Listener propertyButton.Click += (object sender, EventArgs e) => { buttomButtonLayout.RemoveAllViews(); propertyFrameLayout.RemoveAllViews(); propPageScrollView.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.3), GravityFlags.Bottom | GravityFlags.CenterHorizontal); mainPageScrollView.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.7), GravityFlags.Top | GravityFlags.CenterHorizontal); propertyFrameLayout.AddView(GetPropertyLayout(con)); }; //scrollView propPageScrollView = new ScrollView(con); propPageScrollView.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.3), GravityFlags.Bottom | GravityFlags.CenterHorizontal); propPageScrollView.AddView(propertyFrameLayout); frame.AddView(propPageScrollView); frame.AddView(buttomButtonLayout); frame.FocusableInTouchMode = true; return(frame); }
private async void LoadData(View v, Controller ctrl) { play = v.FindViewById <Button>(Resource.Id.Home_Play); pause = v.FindViewById <Button>(Resource.Id.Home_Pause); var taskComplete = v.FindViewById <CheckBox>(Resource.Id.Home_TaskComplete); var recentTask = v.FindViewById <Button>(Resource.Id.Home_RecentTask); var recentProject = v.FindViewById <Button>(Resource.Id.Home_CurrentProject); var expandableList = v.FindViewById <ExpandableListView>(Android.Resource.Id.List); var pb = new ProgressDialog(_mActivity) { Indeterminate = true }; pb.SetTitle("Loading"); //TODO: This is under the assumption that whatever task is on the top of the recent task list // is the currently logged timer task. Check whether this assumption is valid or not. if (TimeLoggingController.GetInstance().IsTimerRunning()) { ModifyPlayPauseState(true); } play.Click += (sender, args) => { Debug.WriteLine("Play Clicked"); //var timerServiceIntent = new Intent("com.tumasolutions.processdashboard.TimerService"); //var timerServiceConnection = new TimerServiceConnection((MainActivity)this.Activity); //Activity.ApplicationContext.BindService(timerServiceIntent, timerServiceConnection, Bind.AutoCreate); if (TimeLoggingController.GetInstance().WasNetworkAvailable) { Intent intent = new Intent(Activity, typeof(TimerService)); intent.PutExtra("taskId", _currenttaskid); Activity.StartService(intent); } else { AlertDialog.Builder builder = new AlertDialog.Builder(Activity); builder.SetTitle("Previous changes not saved") .SetMessage("An earlier time log entry has not yet been synchronized with the server. Please try again later.") .SetNeutralButton("Okay", (sender2, args2) => { builder.Dispose(); }) .SetCancelable(false); AlertDialog alert = builder.Create(); alert.Show(); } }; pause.Click += (sender, args) => { Debug.WriteLine("Pause Clicked"); Activity.StopService(new Intent(Activity, typeof(TimerService))); Toast.MakeText(this.Activity, "Time Log Entry Saved", ToastLength.Short).Show(); }; taskComplete.CheckedChange += (sender, args) => { string text = ""; if (args.IsChecked) { // Mark a task as complete DateTime convertedTime = Util.GetInstance().GetServerTime(DateTime.UtcNow); //taskDetail.CompletionDate = convertedTime; try { ((MainActivity)(Activity)).Ctrl.UpdateATask(AccountStorage.DataSet, _currenttaskid, null, convertedTime, false); text = "Task Marked Complete"; } catch (CannotReachServerException) { if (pb.IsShowing) { pb.Dismiss(); } Debug.WriteLine("We could not reach the server"); taskComplete.Checked = false; text = "Please check your internet connection and try again."; Toast.MakeText(this.Activity, text, ToastLength.Short).Show(); } catch (StatusNotOkayException) { pb.Dismiss(); taskComplete.Checked = false; //TODO: Should we report this ? text = "An error has occured. Please try again."; Toast.MakeText(this.Activity, text, ToastLength.Short).Show(); } catch (Exception e) { // For any other weird exceptions pb.Dismiss(); taskComplete.Checked = false; // Sending to HockeyApp ExceptionHandler.SaveException(Java.Lang.Throwable.FromException(e), null, null); text = "Unable to make the change. Please try again."; Toast.MakeText(this.Activity, text, ToastLength.Short).Show(); } } else { // Unmark the task try { ((MainActivity)(Activity)).Ctrl.UpdateATask(AccountStorage.DataSet, _currenttaskid, null, null, true); text = "Task Marked Incomplete"; } catch (CannotReachServerException) { if (pb.IsShowing) { pb.Dismiss(); } Debug.WriteLine("We could not reach the server"); taskComplete.Checked = true; text = "Please check your internet connection and try again."; Toast.MakeText(this.Activity, text, ToastLength.Short).Show(); } //TODO: Should we handle this ? catch (StatusNotOkayException) { pb.Dismiss(); taskComplete.Checked = true; text = "An error has occured. Please try again."; Toast.MakeText(this.Activity, text, ToastLength.Short).Show(); } catch (Exception e) { // For any other weird exceptions taskComplete.Checked = true; ExceptionHandler.SaveException(Java.Lang.Throwable.FromException(e), null, null); text = "Unable to make the change. Please try again."; Toast.MakeText(this.Activity, text, ToastLength.Short).Show(); } } Debug.WriteLine("We have changed content "); Toast.MakeText(Activity, text, ToastLength.Short).Show(); }; recentTask.Text = "Loading.."; recentProject.Text = "Loading.."; pb.SetCanceledOnTouchOutside(false); pb.Show(); try { var output = await ctrl.GetRecentTasks(AccountStorage.DataSet); pb.Dismiss(); var recent = output[0]; recentTask.Text = recent.FullName; recentProject.Text = recent.Project.Name; _currenttaskid = recent.Id; _headings.Add(recent.Project.Name, new List <Task>()); output.RemoveAt(0); foreach (Task t in output) { if (_headings.ContainsKey(t.Project.Name)) { List <Task> tt = _headings[t.Project.Name]; tt.Add(t); _headings[t.Project.Name] = tt; } else { List <Task> tt = new List <Task>(); tt.Add(t); _headings[t.Project.Name] = tt; } } //var listAdapter = new TaskAdapter(_mActivity, Android.Resource.Layout.SimpleListItem1, output.ToArray()); var listAdapter = new HomeListAdapter(this.Activity, _headings); expandableList.SetAdapter(listAdapter); //ListAdapter = listAdapter; var refresher = v.FindViewById <SwipeRefreshLayout>(Resource.Id.refresher); refresher.Refresh += async delegate { try { output = await ctrl.GetRecentTasks(AccountStorage.DataSet); recent = output[0]; _headings = new Dictionary <string, List <Task> >(); recentTask.Text = recent.FullName; recentProject.Text = recent.Project.Name; _headings.Add(recent.Project.Name, new List <Task>()); output.RemoveAt(0); foreach (Task t in output) { if (_headings.ContainsKey(t.Project.Name)) { List <Task> tt = _headings[t.Project.Name]; tt.Add(t); _headings[t.Project.Name] = tt; } else { List <Task> tt = new List <Task>(); tt.Add(t); _headings[t.Project.Name] = tt; } } listAdapter = new HomeListAdapter(this.Activity, _headings); expandableList.SetAdapter(listAdapter); refresher.Refreshing = false; } catch (CannotReachServerException) { AlertDialog.Builder builder = new AlertDialog.Builder(Activity); builder.SetTitle("Unable to Connect") .SetMessage("Please check your network connection and try again") .SetNeutralButton("Okay", (sender, args) => { builder.Dispose(); }) .SetCancelable(false); AlertDialog alert = builder.Create(); refresher.Refreshing = false; alert.Show(); } catch (StatusNotOkayException se) { AlertDialog.Builder builder = new AlertDialog.Builder(Activity); builder.SetTitle("An Error has occured") .SetMessage("Error :" + se.GetMessage()) .SetNeutralButton("Okay", (sender, args) => { builder.Dispose(); }) .SetCancelable(false); AlertDialog alert = builder.Create(); refresher.Refreshing = false; alert.Show(); } catch (Exception e) { // For any other weird exceptions AlertDialog.Builder builder = new AlertDialog.Builder(Activity); builder.SetTitle("An Error has occured") .SetNeutralButton("Okay", (sender, args) => { builder.Dispose(); }) .SetMessage("Error :" + e.Message) .SetCancelable(false); AlertDialog alert = builder.Create(); refresher.Refreshing = false; alert.Show(); } }; recentProject.Click += (sender, args) => { ((MainActivity)Activity).ListOfProjectsCallback(recent.Project.Id, recent.Project.Name); }; recentTask.Click += (sender, args) => { ((MainActivity)Activity).PassTaskDetailsInfo(recent.Id, recent.FullName, recent.Project.Name, recent.CompletionDate, recent.EstimatedTime, recent.ActualTime); }; } catch (CannotReachServerException) { pb.Dismiss(); AlertDialog.Builder builder = new AlertDialog.Builder(Activity); builder.SetTitle("Unable to Connect") .SetMessage("Please check your network connection and try again") .SetNeutralButton("Okay", (sender, args) => { builder.Dispose(); }) .SetCancelable(false); AlertDialog alert = builder.Create(); alert.Show(); } catch (StatusNotOkayException se) { pb.Dismiss(); AlertDialog.Builder builder = new AlertDialog.Builder(Activity); builder.SetTitle("An Error has occured") .SetMessage("Error :" + se.GetMessage()) .SetNeutralButton("Okay", (sender, args) => { builder.Dispose(); }) .SetCancelable(false); AlertDialog alert = builder.Create(); alert.Show(); } catch (WebException we) { if (we.Status == WebExceptionStatus.ProtocolError) { var response = we.Response as HttpWebResponse; if (response != null) { Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode); if (response.StatusCode == HttpStatusCode.Forbidden) { try { Toast.MakeText(this.Activity, "Username and password error.", ToastLength.Long).Show(); System.Diagnostics.Debug.WriteLine("We are about to logout"); AccountStorage.ClearStorage(); System.Diagnostics.Debug.WriteLine("Main Activity is :" + Activity == null); System.Diagnostics.Debug.WriteLine("Items in the backstack :" + Activity.FragmentManager.BackStackEntryCount); System.Diagnostics.Debug.WriteLine("Main Activity is :" + Activity == null); Activity.FragmentManager.PopBackStack(null, PopBackStackFlags.Inclusive); System.Diagnostics.Debug.WriteLine("Items in the backstack 2 :" + Activity.FragmentManager.BackStackEntryCount); ((MainActivity)(Activity)).SetDrawerState(false); ((MainActivity)(Activity)).SwitchToFragment(MainActivity.FragmentTypes.Login); } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("We encountered an error :" + e.Message); } } } else { // no http status code available Toast.MakeText(Activity, "Unable to load the data. Please restart the application.", ToastLength.Short).Show(); } } else { // no http status code available Toast.MakeText(Activity, "Unable to load the data. Please restart the application.", ToastLength.Short).Show(); } } catch (Exception e) { // For any other weird exceptions pb.Dismiss(); AlertDialog.Builder builder = new AlertDialog.Builder(Activity); builder.SetTitle("An Error has occured") .SetNeutralButton("Okay", (sender, args) => { builder.Dispose(); }) .SetMessage("Error :" + e.Message) .SetCancelable(false); AlertDialog alert = builder.Create(); alert.Show(); } /* * private void LoadDummyData(View v) * { * * ListView lv = v.FindViewById<ListView>(Android.Resource.Id.List); * var items = new[] { "Vegetables", "Fruits", "Flower Buds", "Legumes", "Bulbs", "Tubers" }; * ArrayAdapter listAdapter = new ArrayAdapter<String>(_mActivity, Android.Resource.Layout.SimpleListItem1, items); * ListAdapter = listAdapter; * * TextView recentTask = v.FindViewById<TextView>(Resource.Id.Home_RecentTask); * recentTask.Text = "Project / Mobile App l1 / Iteration 1 / View Skeletons / Create Android Skeletons / Home Screen "; * * } */ }
public void PictureTaken(object sender, ProcessedCameraPreview.PictureTakenEventArgs ea) { Android.Graphics.Bitmap bmp = ea.Bitmap; Camera camera = ea.Camera; try { Android.Graphics.Bitmap thumbnail = null; int maxThumbnailSize = 96; if (_imageFilter == null) { _lastSavedImageFile = ProcessedCameraPreview.SaveBitmap(this, bmp, PackageName, _topLayer); thumbnail = ProcessedCameraPreview.GetThumbnail(bmp, maxThumbnailSize); bmp.Dispose(); } else { Image <Bgr, Byte> buffer1 = new Image <Bgr, byte>(bmp); bmp.Dispose(); using (ImageFilter filter = _imageFilter.Clone() as ImageFilter) { if (filter is DistorFilter) { //reduce the image size to half because the distor filter used lots of memory Image <Bgr, Byte> tmp = buffer1.PyrDown(); buffer1.Dispose(); buffer1 = tmp; } if (filter.InplaceCapable) { filter.ProcessData(buffer1.Mat, buffer1.Mat); } else { Image <Bgr, Byte> buffer2 = new Image <Bgr, byte>(buffer1.Size); filter.ProcessData(buffer1.Mat, buffer2.Mat); buffer1.Dispose(); buffer1 = buffer2; } } using (Android.Graphics.Bitmap result = buffer1.ToBitmap()) { buffer1.Dispose(); _lastSavedImageFile = ProcessedCameraPreview.SaveBitmap(this, result, PackageName, _topLayer); thumbnail = ProcessedCameraPreview.GetThumbnail(result, maxThumbnailSize); } } _lastCapturedImageButton.SetImageBitmap(thumbnail); } catch (Exception excpt) { this.RunOnUiThread(() => { while (excpt.InnerException != null) { excpt = excpt.InnerException; } AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Error saving file"); alert.SetMessage(excpt.Message); alert.SetPositiveButton("OK", (s, er) => { }); alert.Show(); }); return; } /* * catch (FileNotFoundException e) * { * Android.Util.Log.Debug("Emgu.CV", e.Message); * } * catch (IOException e) * { * Android.Util.Log.Debug("Emgu.CV", e.Message); * } */ /* * try * { * ExifInterface exif = new ExifInterface(f.FullName); * // Read the camera model and location attributes * exif.GetAttribute(ExifInterface.TagModel); * float[] latLng = new float[2]; * exif.GetLatLong(latLng); * // Set the camera make * exif.SetAttribute(ExifInterface.TagMake, "My Phone"); * exif.SetAttribute(ExifInterface.TagDatetime, System.DateTime.Now.ToString()); * } * catch (IOException e) * { * Android.Util.Log.Debug("Emgu.CV", e.Message); * }*/ Toast.MakeText(this, "File Saved.", ToastLength.Short).Show(); camera.StartPreview(); }
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { GetOrderParameters(); var view = inflater.Inflate(Resource.Layout.activity_order_management, container, false); #region Иннициализация переменных Id = view.FindViewById <TextView>(Resource.Id.OrderManagementTextIdValue); Weight = view.FindViewById <TextView>(Resource.Id.OrderManagementTexWeight); Temperature = view.FindViewById <TextView>(Resource.Id.OrderManagementTextTemperature); Battery = view.FindViewById <TextView>(Resource.Id.OrderManagementTexBattery); Illumination = view.FindViewById <TextView>(Resource.Id.OrderManagementTextIllumination); Humidity = view.FindViewById <TextView>(Resource.Id.OrderManagementTextHumidity); //Gate = view.FindViewById<TextView>(Resource.Id.OrderManagementTextGate); Lock = view.FindViewById <TextView>(Resource.Id.OrderManagementTextLock); //Fold = view.FindViewById<TextView>(Resource.Id.OrderManagementTextFold); Events = view.FindViewById <TextView>(Resource.Id.OrderManagementTextEvents); progressBar = view.FindViewById <ProgressBar>(Resource.Id.OrderManagementProgressBar); Status = view.FindViewById <TextView>(Resource.Id.OrderManagementTextStatus); Cost = view.FindViewById <TextView>(Resource.Id.OrderManagementTextCost); Payment = view.FindViewById <TextView>(Resource.Id.OrderManagementTextPayment); btn_Pay = view.FindViewById <Button>(Resource.Id.OrderManagementButtonPay); btn_Photo = view.FindViewById <Button>(Resource.Id.OrderManagementButtonPhoto); btn_Video = view.FindViewById <Button>(Resource.Id.OrderManagementButtonVideo); btn_Lock = view.FindViewById <Button>(Resource.Id.OrderManagementButtonLock); #endregion Id.Click += Id_Click; Events.Click += Events_Click; sweep = view.FindViewById <SwipeRefreshLayout>(Resource.Id.SwipeRefreshLayout); sweep.SetColorSchemeColors(Color.Red, Color.Green, Color.Blue, Color.Yellow); sweep.Refresh += RefreshLayout_Refresh; btn_Lock.Click += delegate { AlertDialog.Builder alert = new AlertDialog.Builder(Activity); if (btn_Lock.Text == "Поднять") { alert.SetTitle("Подтверждение действия"); alert.SetMessage("Вы действительно хотите поднять роллету контейнера?"); alert.SetPositiveButton("Поднять", (senderAlert, args) => { MakeUnLock(); }); alert.SetNegativeButton("Отмена", (senderAlert, args) => { }); } else if (btn_Lock.Text == "Опустить") { alert.SetTitle("Подтверждение действия"); if (StaticOrder.Order_Stage_Id == "3") { LayoutInflater layoutInflater = LayoutInflater.From(Activity); View dialogView = layoutInflater.Inflate(Resource.Layout.modal_transmit_order, null); alert.SetView(dialogView); checkBox = dialogView.FindViewById <CheckBox>(Resource.Id.ManageOrderCheckBox); Date = dialogView.FindViewById <Spinner>(Resource.Id.ManageOrderSpinnerTime); CreateTimeArray(); ArrayAdapter <string> adapter = new ArrayAdapter <string>(Activity, Android.Resource.Layout.SimpleSpinnerItem, Time); adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); Date.Adapter = adapter; Date.ItemSelected += new EventHandler <AdapterView.ItemSelectedEventArgs>(SpinnerClass_ItemSelected); Date.Visibility = ViewStates.Invisible; checkBox.Text = "Погрузка завершена. Контейнер готов к отправке."; checkBox.Click += delegate { check = checkBox.Checked; Date.Visibility = ViewStates.Visible; Date.Focusable = false; Date.Clickable = false; }; } else if (StaticOrder.Order_Stage_Id == "6") { LayoutInflater layoutInflater = LayoutInflater.From(Activity); View dialogView = layoutInflater.Inflate(Resource.Layout.modal_transmit_order, null); alert.SetView(dialogView); checkBox = dialogView.FindViewById <CheckBox>(Resource.Id.ManageOrderCheckBox); Date = dialogView.FindViewById <Spinner>(Resource.Id.ManageOrderSpinnerTime); CreateTimeArray(); ArrayAdapter <string> adapter = new ArrayAdapter <string>(Activity, Android.Resource.Layout.SimpleSpinnerItem, Time); adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); Date.Adapter = adapter; Date.ItemSelected += new EventHandler <AdapterView.ItemSelectedEventArgs>(SpinnerClass_ItemSelected); Date.Visibility = ViewStates.Invisible; checkBox.Text = "Разгрузка завершена. Контейнер готов к отправке."; checkBox.Click += delegate { check = checkBox.Checked; Date.Visibility = ViewStates.Visible; Date.Focusable = false; Date.Clickable = false; }; } alert.SetMessage("Вы действительно хотите опустить роллету контейнера?"); alert.SetPositiveButton("Опустить", (senderAlert, args) => { MakeLock(check); if (check == true) { Transmitt(); } FragmentTransaction transaction1 = this.FragmentManager.BeginTransaction(); ManageOrderActivity content2 = new ManageOrderActivity(); transaction1.Replace(Resource.Id.framelayout, content2).AddToBackStack(null).Commit(); }); } Dialog dialog = alert.Create(); dialog.Show(); // } }; btn_Pay.Click += delegate { if (Payment.Text == "неизвестно") { Toast.MakeText(Activity, "В настоящий момент невозможно использовать эту кнопку!\nПричина: Неизвестно состояние об оплате.", ToastLength.Long).Show(); } else { AlertDialogCreation("Внесение оплаты", "Вы действительно хотите оплатить заказ?"); } }; btn_Photo.Click += delegate { AlertDialogCreation("Сделать фотографию", "Вы действительно хотите сделать фотографию с камеры контейнера?"); }; btn_Video.Click += delegate { AlertDialogCreation("Сделать видео", "Вы действительно хотите сделать видео с камеры контейнера?"); }; return(view); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.CreateAccount); var image1 = FindViewById <ImageView>(Resource.Id.imageView1); var edtUser = FindViewById <EditText>(Resource.Id.edTxtUserName); var edtPass = FindViewById <EditText>(Resource.Id.edTxtPassword); var edtConf = FindViewById <EditText>(Resource.Id.edTxtConfPassword); var btnCreate = FindViewById <Button>(Resource.Id.btnCreateAccount); string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "dbUser.db3"); btnCreate.Click += delegate { var db = new SQLiteConnection(dbPath); var table = db.Table <LogIn>(); if (edtUser.Text == "") { AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); alertDialog.SetTitle("Error"); alertDialog.SetMessage("Invalid Username"); alertDialog.SetNeutralButton("OK", delegate { alertDialog.Dispose(); }); alertDialog.Show(); } else if (edtPass.Text == "") { AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); alertDialog.SetTitle("Error"); alertDialog.SetMessage("Invalid Password"); alertDialog.SetNeutralButton("OK", delegate { alertDialog.Dispose(); }); alertDialog.Show(); } else if (edtPass.Text != edtConf.Text) { AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); alertDialog.SetTitle("Error"); alertDialog.SetMessage("Passwords are not the same"); alertDialog.SetNeutralButton("OK", delegate { alertDialog.Dispose(); }); alertDialog.Show(); } else { Boolean allow = true; foreach (var item in table) { if (item.UserName == edtUser.Text) { allow = false; AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); alertDialog.SetTitle("Error"); alertDialog.SetMessage("Username is already in use"); alertDialog.SetNeutralButton("OK", delegate { alertDialog.Dispose(); }); alertDialog.Show(); } } if (allow) { LogIn newLogIn = new LogIn(); newLogIn.UserName = edtUser.Text; newLogIn.Password = edtPass.Text; db.Insert(newLogIn); StartActivity(typeof(MainActivity)); } } }; }
void IPickerRenderer.OnClick() { DoublePicker model = (DoublePicker)Element; if (_dialog != null) return; var layout = new LinearLayout(Context) { Orientation = Orientation.Horizontal }; var picker = new NumberPicker(Context); if (model.Items != null && model.Items.Any()) { picker.MaxValue = model.Items.Count - 1; picker.MinValue = 0; picker.SetDisplayedValues(model.Items.ToArray()); picker.WrapSelectorWheel = false; picker.DescendantFocusability = DescendantFocusability.BlockDescendants; picker.Value = model.SelectedIndexes[0]; picker.TextAlignment = AViews.TextAlignment.Center; } picker.LayoutParameters = new TableLayout.LayoutParams(LayoutParams.WrapContent, LayoutParams.MatchParent, 0.5f); layout.AddView(picker); var picker2 = new NumberPicker(Context); if (model.SecondaryItems != null && model.SecondaryItems.Any()) { picker2.MaxValue = model.SecondaryItems.Count - 1; picker2.MinValue = 0; picker2.SetDisplayedValues(model.SecondaryItems.ToArray()); picker2.WrapSelectorWheel = false; picker2.DescendantFocusability = DescendantFocusability.BlockDescendants; picker2.Value = model.SelectedIndexes[1]; picker2.TextAlignment = AViews.TextAlignment.Center; } picker2.LayoutParameters = new TableLayout.LayoutParams(LayoutParams.WrapContent, LayoutParams.MatchParent, 0.5f); layout.AddView(picker2); ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, true); var builder = new AlertDialog.Builder(Context); builder.SetView(layout); if (!Element.IsSet(Picker.TitleColorProperty)) { builder.SetTitle(model.Title ?? ""); } else { var title = new SpannableString(model.Title ?? ""); title.SetSpan(new ForegroundColorSpan(model.TitleColor.ToAndroid()), 0, title.Length(), SpanTypes.ExclusiveExclusive); builder.SetTitle(title); } builder.SetNegativeButton(global::Android.Resource.String.Cancel, (s, a) => { ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); _dialog = null; }); builder.SetPositiveButton(global::Android.Resource.String.Ok, (s, a) => { var doublePicker = Element as DoublePicker; if (doublePicker != null) { var selectedIndexes = new int[] { picker.Value, picker2.Value }; ElementController.SetValueFromRenderer(DoublePicker.SelectedIndexesProperty, selectedIndexes); model.RaiseSelectedIndexesChanged(selectedIndexes); //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. string text = null; if (doublePicker.Items.Count > 0 && selectedIndexes[0] >= 0) text = doublePicker.Items[selectedIndexes[0]]; if (doublePicker.SecondaryItems.Count > 0 && selectedIndexes[1] >= 0) text = $"{text}{doublePicker.Separator}{doublePicker.SecondaryItems[selectedIndexes[1]]}".Trim(); Control.Text = text; ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); } _dialog = null; }); _dialog = builder.Create(); _dialog.DismissEvent += (sender, args) => { ElementController?.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); _dialog?.Dispose(); _dialog = null; }; _dialog.Show(); }
public override bool OnContextItemSelected(IMenuItem item) { switch (item.ItemId) { case Resource.Id.item_delete: try { mediaPlayer.DeleteSong(selectedSong.Id); UpdateList(); } catch (Exception ex) { GoogleAnalyticsService.Instance.TrackAppException(ex.Message, false); Toast.MakeText(Application.Context, "could not delete this song", ToastLength.Long).Show(); } return(true); case Resource.Id.item_play: Play(selectedSong.Id); Intent intent = new Intent(this, typeof(CurrentSong)); intent.AddFlags(ActivityFlags.SingleTop); StartActivity(intent); return(true); case Resource.Id.item_rename: RenameSong(); return(true); case Resource.Id.seek_bar: AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); seekbarview = new SeekbarView(alertDialogBuilder.Context, null); alertDialogBuilder.SetView(seekbarview); alertDialogBuilder.SetCancelable(false); alertDialogBuilder.SetPositiveButton("OK", (s, e) => { seekbarview.AbortSeekbarThread(); }); alertDialogBuilder.SetTitle(GetSelectedSongTitle()); Drawable picture = SongMetadata.GetSongPicture(selectedSong.Id); if (picture != null) { alertDialogBuilder.SetIcon(picture); } else { alertDialogBuilder.SetIcon(Resource.Drawable.default_song_image); } seekbarDialog = alertDialogBuilder.Create(); seekbarDialog.Show(); return(true); default: return(base.OnContextItemSelected(item)); } }
public View GetSampleContent(Context con) { ScrollView scroll = new ScrollView(con); bool isTablet = SfMaskedEditText.IsTabletDevice(con); LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(12, 12, 12, 12); TextView headLabel = new TextView(con); headLabel.TextSize = 30; headLabel.SetTextColor(Color.ParseColor("#262626")); headLabel.Typeface = Typeface.DefaultBold; headLabel.Text = "Funds Transfer"; linear.AddView(headLabel); TextView fundTransferLabelSpacing = new TextView(con); fundTransferLabelSpacing.SetHeight(40); linear.AddView(fundTransferLabelSpacing); TextView textToAccount = new TextView(con); textToAccount.SetTextColor(Color.ParseColor("#6d6d72")); textToAccount.TextSize = 16; textToAccount.Typeface = Typeface.Default; textToAccount.Text = "To Account"; textToAccount.SetPadding(0, 0, 0, 10); linear.AddView(textToAccount); sfToAccount = new SfMaskedEdit(con); sfToAccount.Mask = "0000 0000 0000 0000"; sfToAccount.Gravity = GravityFlags.Start; sfToAccount.ValidationMode = InputValidationMode.KeyPress; sfToAccount.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; sfToAccount.Hint = "1234 1234 1234 1234"; sfToAccount.SetHintTextColor(Color.LightGray); sfToAccount.ClearButtonVisibility = ClearButtonVisibilityMode.WhileEditing; linear.AddView(sfToAccount); erroToAccount = new TextView(con); erroToAccount.SetTextColor(Color.Red); erroToAccount.TextSize = 12; erroToAccount.Typeface = Typeface.Default; linear.AddView(erroToAccount); TextView textDesc = new TextView(con); textDesc.Text = "Description"; textDesc.Typeface = Typeface.Default; textDesc.SetPadding(0, 30, 0, 10); textDesc.TextSize = 16; linear.AddView(textDesc); sfDesc = new SfMaskedEdit(con); sfDesc.Mask = ""; sfDesc.Gravity = GravityFlags.Start; sfDesc.ValidationMode = InputValidationMode.KeyPress; sfDesc.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; sfDesc.Hint = "Enter description"; sfDesc.SetHintTextColor(Color.LightGray); sfDesc.ClearButtonVisibility = ClearButtonVisibilityMode.WhileEditing; linear.AddView(sfDesc); TextView textAmount = new TextView(con); textAmount.Text = "Amount"; textAmount.Typeface = Typeface.Default; textAmount.SetPadding(0, 30, 0, 10); textAmount.TextSize = 16; linear.AddView(textAmount); amountMask = new SfMaskedEdit(con); amountMask.Mask = "$ 0,000.00"; amountMask.Gravity = GravityFlags.Start; amountMask.ValidationMode = InputValidationMode.KeyPress; amountMask.ValueMaskFormat = MaskFormat.IncludePromptAndLiterals; amountMask.Hint = "$ 3,874.00"; amountMask.SetHintTextColor(Color.LightGray); amountMask.ClearButtonVisibility = ClearButtonVisibilityMode.WhileEditing; linear.AddView(amountMask); errotextAmount = new TextView(con); errotextAmount.SetTextColor(Color.Red); errotextAmount.TextSize = 12; errotextAmount.Typeface = Typeface.Default; linear.AddView(errotextAmount); TextView textEmail = new TextView(con); textEmail.Text = "Email ID"; textEmail.Typeface = Typeface.Default; textEmail.SetPadding(0, 30, 0, 10); textEmail.TextSize = 16; linear.AddView(textEmail); emailMask = new SfMaskedEdit(con); emailMask.Mask = @"\w+@\w+\.\w+"; emailMask.MaskType = MaskType.RegEx; emailMask.Gravity = GravityFlags.Start; emailMask.ValidationMode = InputValidationMode.KeyPress; emailMask.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; emailMask.Hint = "*****@*****.**"; emailMask.SetHintTextColor(Color.LightGray); emailMask.ClearButtonVisibility = ClearButtonVisibilityMode.WhileEditing; linear.AddView(emailMask); errotextEmail = new TextView(con); errotextEmail.SetTextColor(Color.Red); errotextEmail.TextSize = 12; errotextEmail.Typeface = Typeface.Default; linear.AddView(errotextEmail); TextView textPhone = new TextView(con); textPhone.Text = "Mobile Number "; textPhone.Typeface = Typeface.Default; textPhone.SetPadding(0, 30, 0, 10); textPhone.TextSize = 16; linear.AddView(textPhone); phoneMask = new SfMaskedEdit(con); phoneMask.Mask = "+1 000 000 0000"; phoneMask.Gravity = GravityFlags.Start; phoneMask.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; phoneMask.ValidationMode = InputValidationMode.KeyPress; phoneMask.Hint = "+1 323 339 3392"; phoneMask.SetHintTextColor(Color.LightGray); phoneMask.ClearButtonVisibility = ClearButtonVisibilityMode.WhileEditing; linear.AddView(phoneMask); errotextPhone = new TextView(con); errotextPhone.SetTextColor(Color.Red); errotextPhone.TextSize = 12; errotextPhone.Typeface = Typeface.Default; linear.AddView(errotextPhone); TextView searchButtonSpacing = new TextView(con); searchButtonSpacing.SetHeight(30); Button searchButton = new Button(con); searchButton.SetWidth(ActionBar.LayoutParams.MatchParent); searchButton.SetHeight(40); searchButton.Text = "TRANSFER MONEY"; searchButton.SetTextColor(Color.White); searchButton.SetBackgroundColor(Color.Gray); searchButton.Click += (object sender, EventArgs e) => { if (string.IsNullOrEmpty(sfToAccount.Text) || string.IsNullOrEmpty(sfDesc.Text) || string.IsNullOrEmpty(amountMask.Text) || string.IsNullOrEmpty(emailMask.Text) || string.IsNullOrEmpty(phoneMask.Text)) { resultsDialog.SetMessage("Please fill all the required data!"); } else if ((sfToAccount.HasError || sfDesc.HasError || amountMask.HasError || emailMask.HasError || phoneMask.HasError)) { resultsDialog.SetMessage("Please enter valid details"); } else { resultsDialog.SetMessage(string.Format("Amount of {0} has been transferred successfully!", amountMask.Value)); string mask1 = sfToAccount.Mask; sfToAccount.Mask = string.Empty; sfToAccount.Mask = mask1; mask1 = sfDesc.Mask; sfDesc.Mask = "0"; sfDesc.Mask = mask1; mask1 = amountMask.Mask; amountMask.Mask = string.Empty; amountMask.Mask = mask1; mask1 = emailMask.Mask; emailMask.Mask = string.Empty; emailMask.Mask = mask1; mask1 = phoneMask.Mask; phoneMask.Mask = string.Empty; phoneMask.Mask = mask1; } resultsDialog.Create().Show(); }; linear.AddView(searchButtonSpacing); linear.AddView(searchButton); sfToAccount.ValueChanged += SfToAccount_ValueChanged; sfToAccount.MaskInputRejected += SfToAccount_MaskInputRejected; amountMask.ValueChanged += AmountMask_ValueChanged; amountMask.MaskInputRejected += AmountMask_MaskInputRejected; emailMask.ValueChanged += EmailMask_ValueChanged; emailMask.MaskInputRejected += EmailMask_MaskInputRejected; phoneMask.ValueChanged += PhoneMask_ValueChanged; phoneMask.MaskInputRejected += PhoneMask_MaskInputRejected; //results dialog resultsDialog = new AlertDialog.Builder(con); resultsDialog.SetTitle("Status"); resultsDialog.SetPositiveButton("OK", (object sender, DialogClickEventArgs e) => { }); resultsDialog.SetCancelable(true); scroll.AddView(linear); return(scroll); }
/* * public override void OnServiceBound() { * base.OnServiceBound(); * Initialize(); * } */ private void Initialize() { var rawSerials = Intent.GetStringArrayExtra(EXTRA_SERIALS); var type = (EDeviceModel)Intent.GetIntExtra(EXTRA_TEST_TYPE, -1); if (rawSerials == null) { var adb = new AlertDialog.Builder(this); adb.SetTitle("Initialization Error"); adb.SetMessage("Failed to start TestActivity: no serial numbers were passed to the activity"); adb.SetCancelable(false); adb.SetNegativeButton("Cancel", (sender, e) => { Finish(); }); adb.Show(); return; } var sns = new List <ISerialNumber>(); foreach (var raw in rawSerials) { var sn = raw.ParseSerialNumber(); if (sn.deviceModel != type) { var adb = new AlertDialog.Builder(this); adb.SetTitle("Initialization Error"); adb.SetMessage("Failed to start TestActivity: serial number type (" + sn.deviceModel + ") is not the expected: " + type); adb.SetCancelable(false); adb.SetNegativeButton("Well, that sucks", (sender, e) => { Finish(); }); adb.Show(); return; } else { sns.Add(sn); } } if (sns.Count <= 0) { var adb = new AlertDialog.Builder(this); adb.SetTitle("Initialization Error"); adb.SetMessage("No serial numbers were provided to the TestActivity."); adb.SetCancelable(false); adb.SetNegativeButton("Ok. Take me to my leaders", (sender, e) => { Finish(); }); adb.Show(); return; } if (BuildTest(sns)) { InitGrid(); UpdateStartTestButton(); } handler.PostDelayed(() => grid.ReloadData(), 1500); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here int checkedBoxes = 0; int maxChecked = 0; int minChecked = 0; int click = 0; // Set our view from the "main" layout resource SetContentView(Resource.Layout.QuestionBase); var baseLayout = FindViewById <LinearLayout>(Resource.Id.outer); // Get our button from the layout resource, // and attach an event to it Button buttonBack = FindViewById <Button>(Resource.Id.buttonNext); buttonBack.Click += delegate { Finish(); }; TextView textTitle = FindViewById <TextView>(Resource.Id.textTitle); Reader reader = new Reader(); string qtiPath = (string)Intent.Extras.Get("qtiPath"); Stream strm = Assets.Open(qtiPath); XDocument qFile = XDocument.Load(strm); AssesmentItem assessmentItem = reader.Main(qFile); List <VariableDeclaration> declarations = assessmentItem.declerations; List <Block> itemBody = assessmentItem.itemBody; textTitle.Text = assessmentItem.title; foreach (Block b in itemBody) { switch (b.GetType().Name) { #region ChoiceInteraction case "ChoiceInteraction": ChoiceInteraction block = (b as ChoiceInteraction); LinearLayout answerLayout = new LinearLayout(this) { LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent, 2f / itemBody.Count), Orientation = Android.Widget.Orientation.Vertical }; baseLayout.AddView(answerLayout); TextView textPrompt = new TextView(this); ViewGroup.LayoutParams textLayout = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); textPrompt.LayoutParameters = textLayout; textPrompt.TextSize = 20; textPrompt.Text = block.prompt; answerLayout.AddView(textPrompt); maxChecked = block.maxChoices; ViewGroup.LayoutParams checkLayout = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); if (maxChecked == 1) //use radio buttons { RadioGroup rGroup = new RadioGroup(this); LinearLayout.LayoutParams rGroupParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); rGroup.LayoutParameters = rGroupParams; answerLayout.AddView(rGroup); foreach (Choice c in block.choices) { RadioButton choiceButton = new RadioButton(this); choiceButton.LayoutParameters = checkLayout; choiceButton.Text = c.body; rGroup.AddView(choiceButton); } } else //use checkboxes { foreach (Choice c in block.choices) { CheckBox choiceBox = new CheckBox(this); choiceBox.LayoutParameters = checkLayout; choiceBox.Text = c.body; choiceBox.Click += (o, e) => { if (!choiceBox.Checked) { checkedBoxes--; } else if (checkedBoxes < maxChecked) { checkedBoxes++; } else if (maxChecked != 0) { AlertDialog.Builder alertTooMany = new AlertDialog.Builder(this); alertTooMany.SetTitle("Too Many Selections"); alertTooMany.SetMessage("The maximum amount of selections for this question is: " + maxChecked); alertTooMany.SetPositiveButton("Okay", (senderAlert, args) => { alertTooMany.Dispose(); choiceBox.Toggle(); }); alertTooMany.SetCancelable(false); alertTooMany.Show(); } }; answerLayout.AddView(choiceBox); } } break; #endregion case "Block": LinearLayout blockLayout = new LinearLayout(this) { LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 0, 1f / itemBody.Count), Orientation = Android.Widget.Orientation.Horizontal }; baseLayout.AddView(blockLayout); foreach (BlockElement e in b.blockElements) { if ((e as P).inline.GetType().Name == "Image") // add an image block { ImageView image = new ImageView(this); Inline target = (e as P).inline; string imgSrc = (target as Image).source; var resourceId = (int)typeof(Resource.Drawable).GetField(imgSrc).GetValue(null); image.SetImageResource(resourceId); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); layoutParams.Gravity = GravityFlags.Center; image.LayoutParameters = layoutParams; image.Click += (o, x) => { ImageView bigImage = new ImageView(this); bigImage.SetImageResource(resourceId); LinearLayout.LayoutParams layoutParamsBig = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent); layoutParams.Gravity = GravityFlags.CenterHorizontal; bigImage.LayoutParameters = layoutParamsBig; bigImage.Click += (a, c) => { SetContentView(baseLayout); }; SetContentView(bigImage); }; blockLayout.AddView(image); } else if ((e as P).inline.GetType().Name == "Inline") // add a text block { TextView inlineText = new TextView(this); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); layoutParams.Gravity = GravityFlags.Center; inlineText.LayoutParameters = layoutParams; inlineText.Text = (e as P).inline.content; inlineText.TextSize = 15; blockLayout.AddView(inlineText); } } break; default: //textFlavour.Text += b.GetType().Name + "\n"; break; } } //textPrompt.Text = (itemBody[2] as ChoiceInteraction).prompt; //string res= ""; //foreach (Choice c in (itemBody[2] as ChoiceInteraction).choices) //{ // res += c.ToString() + "\n"; //} //textChoices.Text = res; //}; }
private bool BuildTest(List <ISerialNumber> serialNumbers) { var address = Intent.GetStringExtra(EXTRA_RIG_ADDRESS); var type = (EDeviceModel)Intent.GetIntExtra(EXTRA_TEST_TYPE, -1); service = AppService.INSTANCE; var rig = service.GetRigByAddress(address); if (rig == null) { var adb = new AlertDialog.Builder(this); adb.SetTitle("Initialization Error"); adb.SetMessage("Failed to find Rig."); adb.SetCancelable(false); adb.SetNegativeButton("Then how did I get here? Ok, take me back...", (sender, e) => { Finish(); }); adb.Show(); return(false); } else if (rig.rigType != type.AsRigType()) { var adb = new AlertDialog.Builder(this); adb.SetTitle("Initialization Error"); adb.SetMessage("Received a Rig of type: " + rig.rigType + ". A rig of this type is incompatible with a test designed for " + type); adb.SetCancelable(false); adb.SetNegativeButton("This app just refuses to work. Ok, take me back...", (sender, e) => { Finish(); }); adb.Show(); return(false); } else { var connections = new List <IConnection>(); foreach (var serialNumber in serialNumbers) { // TODO [email protected]: This is bad var connection = service.GetConnection(serialNumber); if (connection != null) { connections.Add(connection); } } var tp = new XmlTestParser().Parse(EmbeddedResource.Load(typeof(TestActivity).GetTypeInfo().Assembly, "test_av760.xml")); switch (rig.rigType) { case ERigType.Vacuum: test = new AV760Test(tp, rig as VacuumRig, connections); break; default: var adb = new AlertDialog.Builder(this); adb.SetTitle("Initialization Error"); adb.SetMessage("Failed to build test"); adb.SetCancelable(false); adb.SetNegativeButton("Wai?! Ok, take me back...", (sender, e) => { Finish(); }); adb.Show(); return(false); } service.currentTest = test; test.onTestEvent += OnTestEvent; return(true); } }
protected override void OnCreate(Bundle savedInstanceState) { try { base.OnCreate(savedInstanceState); if (VariablesGlobales.Idvendedor == 0) { Intent i = new Intent(this.ApplicationContext, typeof(MainActivity)); i.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTop); StartActivity(i); this.Finish(); } SetContentView(Resource.Layout.PaginaConfiguracion); var btnVaciarProductos = FindViewById <Button>(Resource.Id.btnVaciarProductos); //var btnVaciarCategoriasProductos = FindViewById<Button>(Resource.Id.btnVaciarCategorias); var btnVaciarListasPrecio = FindViewById <Button>(Resource.Id.btnVaciarListasPrecio); var btnVaciarClientes = FindViewById <Button>(Resource.Id.btnVaciarClientes); var btnVaciarPedidos = FindViewById <Button>(Resource.Id.btnVaciarPedidos); //var btnVaciarPedidosDetalle = FindViewById<Button>(Resource.Id.btnVariarDetallePed); var btnGuardarCotizacionMoneda = FindViewById <Button>(Resource.Id.btnCotizacionDolar); var btnVolver = FindViewById <Button>(Resource.Id.btnConfVolverInicio); var txtCotizacion = FindViewById <EditText>(Resource.Id.txtCotizacionDolar); var txtMetodoCalculo = FindViewById <EditText>(Resource.Id.txtMetodoCalculo); var txtDireccionWebService = FindViewById <EditText>(Resource.Id.txtDireccionWebService); var txtNomWebService = FindViewById <EditText>(Resource.Id.txtNombWebService); SeleccListaPrecios = (Spinner)FindViewById(Resource.Id.spnListaPrecios); //dbUser = new ConsultasTablas(); ListasPrecio = db.VerListaPrecio(); ListaVendedor = db.VerListaPreciosVendedor(VariablesGlobales.Idvendedor); adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, ListasPrecio); SeleccListaPrecios.Adapter = adapter; int posicion = 0; for (int i = 0; i < SeleccListaPrecios.Count; i++) { if (SeleccListaPrecios.GetItemAtPosition(i).ToString() == ListaVendedor[0].nombre) { posicion = i; } } //Toast.MakeText(this, "posicion " + posicion, ToastLength.Long).Show(); SeleccListaPrecios.ItemSelected += new EventHandler <AdapterView.ItemSelectedEventArgs>(ListasPrecios_ItemSelected); MonedaYConfig = db.VerListaConfiguraciones(); txtCotizacion.Text = MonedaYConfig[1].valor; txtMetodoCalculo.Text = MonedaYConfig[2].valor; txtDireccionWebService.Text = MonedaYConfig[4].valor; txtNomWebService.Text = MonedaYConfig[5].valor; SeleccListaPrecios.SetSelection(posicion); if (int.Parse(MonedaYConfig[3].valor) != 0) { ListasPrecio = new List <ListasPrecio>(); ListasPrecio = db.VerListaPrecioId(int.Parse(MonedaYConfig[3].valor)); int itemSel = adapter.GetPosition(ListasPrecio[0].nombre); } btnVaciarProductos.Click += delegate { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Specify Action"); alert.SetMessage("Esta seguro que desea vaciar la tabla de productos?"); alert.SetPositiveButton("Aceptar", (senderAlert, args) => { if (db.VaciarTablaProductos()) { Toast.MakeText(this, "Se vacio la tabla de PRODUCTOS", ToastLength.Long).Show(); } if (db.VaciarTablaCategoriasProd()) { Toast.MakeText(this, "Se vacio la tabla de categorias", ToastLength.Long).Show(); } }); alert.SetNegativeButton("Cancelar", (senderAlert, args) => { Toast.MakeText(this, "Proceso cancelado", ToastLength.Long).Show(); }); Dialog dialog = alert.Create(); dialog.Show(); }; btnVaciarListasPrecio.Click += delegate { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Specify Action"); alert.SetMessage("Esta seguro que desea vaciar la tabla de productos?"); alert.SetPositiveButton("Aceptar", (senderAlert, args) => { if (db.VaciarTablaListasPrecio()) { Toast.MakeText(this, "Se vacio la tabla de LISTAS DE PRECIO", ToastLength.Long).Show(); } }); alert.SetNegativeButton("Cancelar", (senderAlert, args) => { Toast.MakeText(this, "Proceso cancelado", ToastLength.Long).Show(); }); Dialog dialog = alert.Create(); dialog.Show(); }; btnVaciarClientes.Click += delegate { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Specify Action"); alert.SetMessage("Esta seguro que desea vaciar la tabla de CLIENTES?"); alert.SetPositiveButton("Aceptar", (senderAlert, args) => { if (db.VaciarTablaClientes()) { Toast.MakeText(this, "Se vacio la tabla de Clientes", ToastLength.Long).Show(); } }); alert.SetNegativeButton("Cancelar", (senderAlert, args) => { Toast.MakeText(this, "Proceso cancelado", ToastLength.Long).Show(); }); Dialog dialog = alert.Create(); dialog.Show(); }; btnVaciarPedidos.Click += delegate { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Specify Action"); alert.SetMessage("Esta seguro que desea vaciar la tabla de PEDIDOS?"); alert.SetPositiveButton("Aceptar", (senderAlert, args) => { if (db.VaciarTablaPedidosMaster()) { Toast.MakeText(this, "Se vacio la tabla de Pedidos", ToastLength.Long).Show(); } if (db.VaciarTablaDetallePedidos()) { Toast.MakeText(this, "Se vacio la tabla de Detalle de pedidos", ToastLength.Long).Show(); } }); alert.SetNegativeButton("Cancelar", (senderAlert, args) => { Toast.MakeText(this, "Proceso cancelado", ToastLength.Long).Show(); }); Dialog dialog = alert.Create(); dialog.Show(); }; btnGuardarCotizacionMoneda.Click += delegate { if (listaOK == true) { string ItemLIstaPrecios = SeleccListaPrecios.SelectedItem.ToString(); ListasPrecio = new List <ListasPrecio>(); ListasPrecio = db.ObtenerIDListaPrecios(ItemLIstaPrecios); } double tempCotiza = 0; if (txtCotizacion.Text != "" & double.TryParse(txtCotizacion.Text, out tempCotiza)) { string valLista = "0"; if (listaOK == true) { valLista = ListasPrecio[0].id.ToString(); } else { valLista = "0"; } ConfiguracionesVarias moneda = new ConfiguracionesVarias() { id = 2, valor = txtCotizacion.Text }; ConfiguracionesVarias FormulaCalculo = new ConfiguracionesVarias { id = 3, valor = txtMetodoCalculo.Text }; ConfiguracionesVarias listaDefecto = new ConfiguracionesVarias { id = 4, valor = valLista }; db.ActualizarConfiguracion(moneda); db.ActualizarConfiguracion(FormulaCalculo); db.ActualizarConfiguracion(listaDefecto); VariablesGlobales.CotizacionDolar = double.Parse(txtCotizacion.Text); VariablesGlobales.MetodoCalculo = int.Parse(txtMetodoCalculo.Text); VariablesGlobales.ListaPrecioCliente = int.Parse(valLista); // ListasPrecio[0].id; Toast.MakeText(this, "Se actualizo configuraciones varias", ToastLength.Long).Show(); } else { Toast.MakeText(this, "NO SE PUEDEN GUARDAR LAS CONFIGURACIONES VARIAS", ToastLength.Long).Show(); } if (txtDireccionWebService.Text != "" & txtDireccionWebService.Text.Contains("http://") == true & txtNomWebService.Text != "" & txtNomWebService.Text.Contains("/") == false) { ConfiguracionesVarias DireccWebService = new ConfiguracionesVarias { id = 5, nombre = "DireccWebService", valor = txtDireccionWebService.Text }; ConfiguracionesVarias NombWebService = new ConfiguracionesVarias { id = 6, nombre = "NombWebService", valor = txtNomWebService.Text }; db.ActualizarConfiguracion(DireccWebService); db.ActualizarConfiguracion(NombWebService); VariablesGlobales.DireccWebService = txtDireccionWebService.Text; VariablesGlobales.NombWebService = txtNomWebService.Text; Toast.MakeText(this, "Se actualizo la configuracion de web service", ToastLength.Long).Show(); } else { Toast.MakeText(this, "NO SE PUEDEN GUARDAR LAS CONFIGURACIONES DE WEB SERVICE", ToastLength.Long).Show(); } }; btnVolver.Click += delegate { StartActivity(typeof(PaginaPrincipal)); }; } catch (Exception ex) { Toast.MakeText(Application.Context, ex.Message, ToastLength.Short).Show(); } }
private void AsyncInitCallback() { try { AppInfo._achievesInfo = new Achieves(AppInfo._access_token, AppInfo._user.ItsBetaUserId, AppInfo.IsLocaleRu); } catch { _messageDialogBuilder.SetTitle("Ошибка"); _messageDialogBuilder.SetMessage("Не удалось подключиться. Проверьте состояние интернет подключения."); if (!AppInfo.IsLocaleRu) { _messageDialogBuilder.SetTitle("Error"); _messageDialogBuilder.SetMessage("Internet connection missing."); } if (AppInfo.IsLocaleRu) { _messageDialogBuilder.SetPositiveButton("Ок", delegate { RunOnUiThread(() => Finish()); }); } if (!AppInfo.IsLocaleRu) { _messageDialogBuilder.SetPositiveButton("Оk", delegate { RunOnUiThread(() => Finish()); }); } RunOnUiThread(() => ShowAlertDialog()); RunOnUiThread(() => _progressDialog.Dismiss()); return; } if (AppInfo.IsLocaleRu) { RunOnUiThread(() => _progressDialogMessage.Text = "Загрузка данных..." ); } if (!AppInfo.IsLocaleRu) { RunOnUiThread(() => _progressDialogMessage.Text = "Loading Data..." ); } Directory.CreateDirectory(@"/data/data/ru.hintsolutions.itsbeta/cache/pictures/"); for (int i = 0; i < AppInfo._achievesInfo.CategoriesCount; i++) { for (int j = 0; j < AppInfo._achievesInfo.CategoryArray[i].Projects.Count(); j++) { AppInfo._subcategCount++; for (int k = 0; k < AppInfo._achievesInfo.CategoryArray[i].Projects[j].Achievements.Count(); k++) { AppInfo._badgesCount++; AppInfo._bonusesCount += AppInfo._achievesInfo.CategoryArray[i].Projects[j].Achievements[k].Bonuses.Count(); FileStream fs = new FileStream(@"/data/data/ru.hintsolutions.itsbeta/cache/pictures/" + AppInfo._achievesInfo.CategoryArray[i].Projects[j].Achievements[k].ApiName + ".PNG", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite ); if (!System.IO.File.Exists(@"/data/data/ru.hintsolutions.itsbeta/cache/pictures/" + "achive" + AppInfo._achievesInfo.CategoryArray[i].Projects[j].Achievements[k].ApiName + ".PNG")) { Bitmap bitmap; try { bitmap = GetImageBitmapFromUrl(AppInfo._achievesInfo.CategoryArray[i].Projects[j].Achievements[k].PicUrl); } catch { if (AppInfo.IsLocaleRu) { _messageDialogBuilder.SetTitle("Ошибка"); _messageDialogBuilder.SetMessage("Ошибка загрузки контента."); _messageDialogBuilder.SetPositiveButton("Ок", delegate { RunOnUiThread(() => Finish()); }); } if (!AppInfo.IsLocaleRu) { _messageDialogBuilder.SetTitle("Error"); _messageDialogBuilder.SetMessage("Content load error."); _messageDialogBuilder.SetPositiveButton("Оk", delegate { RunOnUiThread(() => Finish()); }); } RunOnUiThread(() => ShowAlertDialog()); RunOnUiThread(() => _progressDialog.Dismiss()); return; } bitmap.Compress( Bitmap.CompressFormat.Png, 10, fs); bitmap.Recycle(); bitmap.Dispose(); fs.Flush(); fs.Close(); System.IO.File.Copy(@"/data/data/ru.hintsolutions.itsbeta/cache/pictures/" + AppInfo._achievesInfo.CategoryArray[i].Projects[j].Achievements[k].ApiName + ".PNG", @"/data/data/ru.hintsolutions.itsbeta/cache/pictures/" + "achive" + AppInfo._achievesInfo.CategoryArray[i].Projects[j].Achievements[k].ApiName + ".PNG"); System.IO.File.Delete(@"/data/data/ru.hintsolutions.itsbeta/cache/pictures/" + AppInfo._achievesInfo.CategoryArray[i].Projects[j].Achievements[k].ApiName + ".PNG"); } } } } RunOnUiThread(() => OnDataLoadingComplete()); }
void DisplayMessageBox( string title, string message, Note.MessageBoxResult onResult ) { Rock.Mobile.Threading.Util.PerformOnUIThread( delegate { AlertDialog.Builder dlgAlert = new AlertDialog.Builder( Rock.Mobile.PlatformSpecific.Android.Core.Context ); dlgAlert.SetTitle( title ); dlgAlert.SetMessage( message ); dlgAlert.SetNeutralButton( GeneralStrings.Yes, delegate { onResult( 0 ); }); dlgAlert.SetPositiveButton( GeneralStrings.No, delegate(object sender, DialogClickEventArgs ev ) { onResult( 1 ); } ); dlgAlert.Create( ).Show( ); } ); }