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 SetNegativeButton(string text, EventHandler <DialogClickEventArgs> handler) { if (_useAppCompat) { _appcompatBuilder?.SetNegativeButton(text, handler); } else { _legacyBuilder?.SetNegativeButton(text, handler); } }
/// <summary> /// Shows the message box. /// </summary> /// <param name="message">The message.</param> /// <param name="caption">The caption.</param> /// <param name="button">The button.</param> /// <param name="icon">The icon.</param> /// <returns>The message result.</returns> /// <exception cref="ArgumentException">The <paramref name="message"/> is <c>null</c> or whitespace.</exception> protected virtual Task<MessageResult> ShowMessageBox(string message, string caption = "", MessageButton button = MessageButton.OK, MessageImage icon = MessageImage.None) { var messageResult = MessageResult.Cancel; var context = Catel.Android.ContextHelper.CurrentContext; var builder = new AlertDialog.Builder(context); switch (button) { case MessageButton.OK: builder.SetPositiveButton("OK", (sender, e) => { messageResult = MessageResult.OK; }); break; case MessageButton.OKCancel: builder.SetPositiveButton("OK", (sender, e) => { messageResult = MessageResult.OK; }); builder.SetCancelable(true); break; case MessageButton.YesNo: builder.SetPositiveButton("Yes", (sender, e) => { messageResult = MessageResult.Yes; }); builder.SetNegativeButton("No", (sender, e) => { messageResult = MessageResult.No; }); break; case MessageButton.YesNoCancel: builder.SetPositiveButton("Yes", (sender, e) => { messageResult = MessageResult.Yes; }); builder.SetNegativeButton("No", (sender, e) => { messageResult = MessageResult.No; }); builder.SetCancelable(true); break; default: throw new ArgumentOutOfRangeException("button"); } return Task<MessageResult>.Run(() => { builder.SetMessage(message).SetTitle(caption); builder.Show(); return messageResult; }); }
public override Task <QuestionResponse <TResponse> > AskQuestionAsync <TResponse>( IQuestion <TResponse> question) { Context context = ResolveContext(); AlertDialog.Builder builder = new AlertDialog.Builder(context); var trq = question as TextQuestion; if (trq == null) { throw new NotSupportedException( "Only TextQuestion is supported at this time."); } var caption = trq.Caption; if (!string.IsNullOrWhiteSpace(caption)) { builder.SetTitle(caption.Parse()); } var message = trq.Question; if (!string.IsNullOrWhiteSpace(message)) { builder.SetMessage(message.Parse()); } EditText editText = new EditText(context); if (trq.InputScope != InputScopeNameValue.Default) { var converter = Dependency.Resolve <IAndroidInputScopeConverter>(); var platformValue = converter.ToNativeType(trq.InputScope); editText.InputType = platformValue; } if (!trq.MultiLine) { editText.SetSingleLine(true); editText.SetMaxLines(1); } if (!trq.SpellCheckEnabled) { editText.InputType = editText.InputType | InputTypes.TextFlagNoSuggestions; } if (trq.InputScope == InputScopeNameValue.Password || trq.InputScope == InputScopeNameValue.NumericPassword) { editText.TransformationMethod = new PasswordTransformationMethod(); } //var color = context.Resources.GetColor(Resources.Color.dialog_textcolor); //textBox.SetTextColor(Color.Black); editText.Text = trq.DefaultResponse; builder.SetView(editText); var manager = (InputMethodManager)context.GetSystemService(Context.InputMethodService); var source = new TaskCompletionSource <QuestionResponse <TResponse> >(); builder.SetPositiveButton(Strings.Okay(), (s, e) => { Interlocked.Decrement(ref openDialogCount); var textReponse = new TextResponse(OkCancelQuestionResult.OK, editText.Text); var result = new QuestionResponse <TResponse>((TResponse)(object)textReponse, question); manager.HideSoftInputFromWindow(editText.WindowToken, HideSoftInputFlags.None); source.TrySetResult(result); }); builder.SetNegativeButton(Strings.Cancel(), (s, e) => { Interlocked.Decrement(ref openDialogCount); var textReponse = new TextResponse { OkCancelQuestionResult = OkCancelQuestionResult.Cancel }; var result = new QuestionResponse <TResponse>((TResponse)(object)textReponse, question); manager.HideSoftInputFromWindow(editText.WindowToken, HideSoftInputFlags.None); source.TrySetResult(result); }); Interlocked.Increment(ref openDialogCount); var dialog = builder.Show(); dialog.SetCanceledOnTouchOutside(false); /* Focussing the EditText and showing the keyboard, * must be done after the alert is show, else it has no effect. */ var looper = context.MainLooper; var handler = new Handler(looper); handler.Post(() => { editText.RequestFocus(); manager.ShowSoftInput(editText, ShowFlags.Forced); }); return(source.Task); }
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); }
void basesList_ItemClick(object sender, AdapterView.ItemClickEventArgs e) { if (e.Position < _manager.Infobases.Length) { InfobaseManager.Infobase currentInfobase = _manager.Infobases[e.Position]; foreach (var infobase in _manager.Infobases) { if (infobase != currentInfobase) { infobase.IsActive = false; } } var settings = new Settings(_prefs, Activity.Resources.Configuration.Locale.Language, currentInfobase); _resultCallback(settings); } else { using (var builder = new AlertDialog.Builder(Activity)) { builder.SetTitle(D.CREATE_NEW_INFOBASE); var ll = new LinearLayout(Activity) { Orientation = Orientation.Vertical }; ll.SetPadding(10, 5, 10, 5); builder.SetView(ll); ll.AddView(new TextView(Activity) { Text = D.INFOBASE_NAME }); var editName = new EditText(Activity); editName.SetSingleLine(); ll.AddView(editName); ll.AddView(new TextView(Activity) { Text = D.URL }); var editUrl = new EditText(Activity) { Text = "http://" }; editUrl.SetSingleLine(); ll.AddView(editUrl); ll.AddView(new TextView(Activity) { Text = D.APPLICATION }); var editApplication = new EditText(Activity) { Text = "app" }; editApplication.SetSingleLine(); ll.AddView(editApplication); ll.AddView(new TextView(Activity) { Text = D.FTP_PORT }); var editFtpPort = new EditText(Activity) { Text = "21" }; editFtpPort.SetSingleLine(); ll.AddView(editFtpPort); builder.SetPositiveButton(D.OK, (s, args) => { _manager.CreateInfobase(editName.Text, editUrl.Text , editApplication.Text, editFtpPort.Text); LoadList(); }); builder.SetNegativeButton(D.CANCEL, (s, args) => { }); builder.Show(); } } }
public void SaveBtn_Click(object sender, EventArgs args) { if (napomeneInput.Text.Length > 512) { return; } string lokacijaNaziv = db.Query <DID_Lokacija>( "SELECT * " + "FROM DID_Lokacija " + "WHERE SAN_Id = ?", lokacijaId).FirstOrDefault().SAN_Naziv; DID_RadniNalog_Lokacija radniNalogLokacija = db.Query <DID_RadniNalog_Lokacija>( "SELECT * " + "FROM DID_RadniNalog_Lokacija " + "WHERE Id = ?", radniNalogLokacijaId).FirstOrDefault(); if (radniNalogLokacija.Status == 3) { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Upozorenje!"); alert.SetMessage("Dodavanjem ankete lokacija " + lokacijaNaziv + " gubi status izvršene lokacije. Jeste li sigurni da želite nastaviti?"); alert.SetPositiveButton("NASTAVI", (senderAlert, arg) => { SpremiAnketu(); db.Execute( "UPDATE DID_RadniNalog_Lokacija " + "SET Status = 2, " + "SinhronizacijaStatus = 0 " + "WHERE Id = ?", radniNalogLokacijaId); db.Execute( "UPDATE DID_Lokacija " + "SET SinhronizacijaStatus = 0 " + "WHERE SAN_Id = ?", lokacijaId); DID_RadniNalog radniNalog = db.Query <DID_RadniNalog>( "SELECT * " + "FROM DID_RadniNalog " + "WHERE Id = ?", radniNalogId).FirstOrDefault(); if (radniNalog.SinhronizacijaStatus == 2) { db.Query <DID_RadniNalog>( "UPDATE DID_RadniNalog " + "SET SinhronizacijaStatus = 1 " + "WHERE Id = ?", radniNalogId); } List <DID_RadniNalog_Lokacija> zavrseneLokacije = db.Query <DID_RadniNalog_Lokacija>( "SELECT * " + "FROM DID_RadniNalog_Lokacija " + "WHERE RadniNalog = ? " + "AND Status = 3", radniNalogId); if (zavrseneLokacije.Any()) { db.Query <DID_RadniNalog>( "UPDATE DID_RadniNalog " + "SET Status = 4 " + "WHERE Id = ?", radniNalogId); } else { db.Query <DID_RadniNalog>( "UPDATE DID_RadniNalog " + "SET Status = 3 " + "WHERE Id = ?", radniNalogId); } }); alert.SetNegativeButton("ODUSTANI", (senderAlert, arg) => { localPozicija.Edit().Clear().Commit(); localAnketa.Edit().Clear().Commit(); intent = new Intent(this, typeof(Activity_Lokacije)); StartActivity(intent); }); Dialog dialog = alert.Create(); dialog.Show(); } else { SpremiAnketu(); } }
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(ActivityBaseEx.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 }); }
public void letterPressed(View view) { string ltr = ((TextView)view).Text.ToString(); char letterChar = ltr[0]; view.Enabled = false; view.SetBackgroundResource(Resource.Drawable.letter_down); bool correct = false; for (int k = 0; k < current.Length; k++) { if (current[k] == letterChar) { correct = true; corrected++; charViews[k].SetTextColor(Resources.GetColor(Resource.Color.black)); } } if (correct) { if (corrected == numc) { disableBtns(); AlertDialog.Builder winBuild = new AlertDialog.Builder(this); winBuild.SetTitle("Superb ! Winner Winner Chicken Dinner"); winBuild.SetMessage("\n\nCorrect answer :\n\n" + current); points = points + 10; winBuild.SetPositiveButton("Play Again", (c, ev) => { this.playGame(); }); winBuild.SetNegativeButton("Close", (c, ev) => { dataStore.inserscore(this, nameuser, points + ""); StartActivity(new Intent(this, typeof(Result)).PutExtra("name", nameuser).PutExtra("score", points + "")); this.Finish(); }); winBuild.Show(); } } else if (currPart < numParts) { images[currPart].Visibility = ViewStates.Visible; currPart++; } else { disableBtns(); AlertDialog.Builder loseBuild = new AlertDialog.Builder(this); loseBuild.SetTitle("Bad Luck ! You Lost"); loseBuild.SetMessage("\n\nThe correct answer is :\n\n" + current); loseBuild.SetPositiveButton("Start Again", (c, ev) => { this.playGame(); }); loseBuild.SetNegativeButton("Close", (c, ev) => { dataStore.inserscore(this, nameuser, points + ""); StartActivity(new Intent(this, typeof(Result)).PutExtra("name", nameuser).PutExtra("score", points + "")); this.Finish(); }); loseBuild.Show(); } }
public override View GetView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { view = LayoutInflater.From(context).Inflate(Resource.Layout.EventCardView, null); } var message = view.FindViewById <TextView>(Resource.Id.EventCardTextName); var btn_video = view.FindViewById <Button>(Resource.Id.btn_video); view.FindViewById <TextView>(Resource.Id.EventCardTextTime).Text = events[position].Time; view.FindViewById <TextView>(Resource.Id.EventCardTextDate).Text = events[position].Date; if (events[position].ContentType == "image") { btn_video.Visibility = ViewStates.Visible; btn_video.Enabled = true; message.Text = "Сделано фото"; btn_video.Text = "Просмотреть фото"; } else if (events[position].ContentType == "video") { message.Text = "Получено видео"; btn_video.Text = "Просмотреть видео"; btn_video.Visibility = ViewStates.Visible; btn_video.Enabled = true; } else { message.Text = events[position].Name; btn_video.Visibility = ViewStates.Invisible; btn_video.Enabled = false; btn_video.Text = ""; } btn_video.Click += delegate { try { listPosition.Add(position); if (_Clicked == false) { _Clicked = true; AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.SetTitle("Внимание!"); alert.SetMessage("Вы действительно хотите открыть медиа файл?"); alert.SetPositiveButton("Открыть", (senderAlert, args) => { _Clicked = false; MaxElement = listPosition.Max(); if (btn_video.Text == "Просмотреть фото") { SetPhoto(events[MaxElement].Name); } else { GetVideo(); VideoFromServerActivity content = new VideoFromServerActivity(); listPosition.Clear(); manager.Replace(Resource.Id.framelayout, content); manager.Commit(); } }); alert.SetNegativeButton("Отмена", (senderAlert, args) => { _Clicked = false; listPosition.Clear(); }); Dialog dialog = alert.Create(); dialog.Show(); } //if (events[position].ContentType == "image") //{ // string Message = "Фотография успешно получена. Вы можете её посмотреть."; //} //else //{ // string Message = "Видео успешно получено. Вы можете его просмотреть."; //} } catch (Exception ex) { Toast.MakeText(context, ex.Message, ToastLength.Long); } }; return(view); }
public override bool OnOptionsItemSelected(IMenuItem item) { // Handle presses on the action bar items try { switch (item.ItemId) { case Resource.Id.action_paste: pastedText = GetBufText(this); if (pastedText.Length == 0) { Toast.MakeText(this.Application, GetString(Resource.String.msg_empty), ToastLength.Long).Show(); return(true); } SaveFilePos(); annoMode = ANNOTATE_BUFFER; textLen = pastedText.Length; Title = "Chinese Reader"; mBookmarks.Clear(); mFoundBookmarks.Clear(); Annotate(-1); return(true); case Resource.Id.action_open: if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != Permission.Granted) { ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.WriteExternalStorage }, REQUEST_STORAGE_FOR_FILEBROWSER); } else { OpenFileBrowser(); } return(true); case Resource.Id.action_save: if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != Permission.Granted) { ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.WriteExternalStorage }, REQUEST_STORAGE_FOR_SAVE); } else { SaveToFile(); } return(true); case Resource.Id.action_about: AboutDialog about = new AboutDialog(this); about.Show(); return(true); case Resource.Id.menu_starred: if (annTask != null && annTask.status == AsyncTask.Status.Running) { annTask.Cancel(true); } SaveFilePos(); StartActivityForResult(new Intent(this, typeof(StarredActivity)), STARRED_ACTIVITY_CODE); return(true); case Resource.Id.menu_bookmarks: AlertDialog.Builder builderSingle = new AlertDialog.Builder(this); builderSingle.SetIcon(Resource.Drawable.ic_launcher); builderSingle.SetTitle("Bookmarks"); ArrayAdapter <string> arrayAdapter = new ArrayAdapter <string>(this, global::Android.Resource.Layout.SelectDialogItem); for (int i = 0; i < mBookmarks.Count; i++) { arrayAdapter.Add(mBookmarks[i].mTitle); } builderSingle.SetNegativeButton("Cancel", (sender, e) => { ((AlertDialog)sender).Dismiss(); }); builderSingle.SetAdapter(arrayAdapter, (sender, e) => { Annotate(mBookmarks[e.Which].mPosition); }); builderSingle.Show(); return(true); default: if (item.ItemId < 4) { string path = GetPreferences(FileCreationMode.Private).GetString("recent" + item.ItemId, ""); SaveFilePos(); Annotate(path); } return(base.OnOptionsItemSelected(item)); } } catch (Exception e) { Toast.MakeText(this, "Error: " + e.Message, ToastLength.Long).Show(); } return(false); }
public void SpremiBtn_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(kolicinaInput.Text) && Convert.ToDecimal(kolicinaInput.Text) > 0) { int statusLokacije = db.Query <DID_RadniNalog_Lokacija>( "SELECT * " + "FROM DID_RadniNalog_Lokacija " + "WHERE Lokacija = ? " + "AND RadniNalog = ?", lokacijaId, radniNalog).FirstOrDefault().Status; string nazivLokacije = db.Query <DID_Lokacija>( "SELECT * " + "FROM DID_Lokacija " + "WHERE SAN_Id = ?", lokacijaId).FirstOrDefault().SAN_Naziv; if (statusLokacije == 2) { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Upozorenje!"); alert.SetMessage("Lokacija " + nazivLokacije + " je zaključana. Jeste li sigurni da želite nastaviti?"); alert.SetPositiveButton("DA", (senderAlert, arg) => { UpdateMaterijala(); List <DID_RadniNalog_Lokacija> sveLokacije = db.Query <DID_RadniNalog_Lokacija>( "SELECT * " + "FROM DID_RadniNalog_Lokacija " + "WHERE RadniNalog = ?", radniNalog); List <DID_RadniNalog_Lokacija> izvrseneLokacije = db.Query <DID_RadniNalog_Lokacija>( "SELECT * " + "FROM DID_RadniNalog_Lokacija " + "WHERE RadniNalog = ? " + "AND Status = 3", radniNalog); if (sveLokacije.Count == izvrseneLokacije.Count) { db.Query <DID_RadniNalog>( "UPDATE DID_RadniNalog " + "SET Status = ?, DatumIzvrsenja = ? " + "WHERE Id = ?", 5, DateTime.Now, radniNalog); } else if (izvrseneLokacije.Any()) { db.Query <DID_RadniNalog>( "UPDATE DID_RadniNalog " + "SET Status = ? " + "WHERE Id = ?", 4, radniNalog); } else { db.Query <DID_RadniNalog>( "UPDATE DID_RadniNalog " + "SET Status = ? " + "WHERE Id = ?", 3, radniNalog); } if (localMaterijali.GetBoolean("potvrda", false)) { intent = new Intent(this, typeof(Activity_Potvrda_page4)); } else if (localMaterijali.GetBoolean("materijaliPoPoziciji", false)) { intent = new Intent(this, typeof(Activity_PotroseniMaterijali_Pozicija)); } else { intent = new Intent(this, typeof(Activity_PotroseniMaterijali)); } StartActivity(intent); }); alert.SetNegativeButton("NE", (senderAlert, arg) => { }); Dialog dialog = alert.Create(); dialog.Show(); } else { UpdateMaterijala(); intent = new Intent(this, typeof(Activity_PotroseniMaterijali_Pozicija)); StartActivity(intent); } } else { messageKolicina.Visibility = Android.Views.ViewStates.Visible; } }
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (resultCode != Result.Ok) { return; } if ((requestCode == SelectBackupId) && (data != null)) { string fileSource = data.GetStringExtra("FullName"); string fileDestination = Android_Database.Instance.GetProductiveDatabasePath(); string message = string.Format("Backup Datenbank\n\n{0}\n\nwiederherstellen in {1}?", Path.GetFileName(fileSource), Path.GetFileName(fileDestination)); var builder = new AlertDialog.Builder(this); builder.SetMessage(message); builder.SetNegativeButton("Abbruch", (s, e) => { }); builder.SetPositiveButton("Ok", (s, e) => { var progressDialog = this.CreateProgressBar(Resource.Id.ProgressBar_BackupAndRestore); new Thread(new ThreadStart(delegate { // Sich neu connecten; Android_Database.Instance.CloseConnection(); // Löschen von '*.db3-shn' und '*.db3-wal' //string deleteFile1 = Path.ChangeExtension(fileDestination, "db3-shm"); //File.Delete(deleteFile1); string deleteFile2 = Path.ChangeExtension(fileDestination, "db3-wal"); if (File.Exists(deleteFile2)) { File.Delete(deleteFile2); } File.Copy(fileSource, fileDestination, true); // Sich neu connecten; Android_Database.SQLiteConnection = null; var databaseConnection = Android_Database.Instance.GetConnection(); var picturesToMove = Android_Database.Instance.GetArticlesToCopyImages(databaseConnection); if (picturesToMove.Count > 0) { RunOnUiThread(() => { message = string.Format( "Es müsen {0} Bilder übetragen werden. Beenden Sie die app ganz und starten Sie diese neu.", picturesToMove.Count); var dialog = new AlertDialog.Builder(this); dialog.SetMessage(message); dialog.SetTitle(Resource.String.App_Name); dialog.SetIcon(Resource.Drawable.ic_launcher); dialog.SetPositiveButton("OK", (s1, e1) => { }); dialog.Create().Show(); }); } RunOnUiThread(() => { this.ShowDatabaseInfo(); this.ShowUserDefinedCategories(); }); this.HideProgressBar(progressDialog); })).Start(); }); builder.Create().Show(); } }
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(); if (EController != null) { EController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); } _dialog = null; Control.ClearFocus(); HideKeyboard(); }); builder.SetPositiveButton(blankPicker.DoneButtonText ?? "OK", (s, a) => { if (EController != null) { 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) => { if (EController != null) { EController?.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); } Control.ClearFocus(); HideKeyboard(); }; _dialog.Show(); }
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(); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); try { SetContentView(Resource.Layout.MyFavoriteGridView); ActionBar.SetHomeButtonEnabled(true); ActionBar.SetDisplayHomeAsUpEnabled(true); if (StoreName == "") { StoreName = Intent.GetStringExtra("MyData"); } this.Title = StoreName; int StoreId = 0; if (StoreName == "My Favorites") { StoreId = 1; } else if (StoreName == "Point Pleasent Store") { StoreId = 2; } else if (StoreName == "Wall Store") { StoreId = 3; } int userId = Convert.ToInt32(CurrentUser.getUserId()); ServiceWrapper sw = new ServiceWrapper(); ItemListResponse output = new ItemListResponse(); output = sw.GetItemFavsUID(userId).Result; List <Item> myArr; myArr = output.ItemList.ToList(); var gridview = FindViewById <GridView>(Resource.Id.gridviewfav); MyFavoriteAdapter adapter = new MyFavoriteAdapter(this, myArr); gridview.SetNumColumns(2); gridview.Adapter = adapter; gridview.ItemClick += delegate(object sender, AdapterView.ItemClickEventArgs args) { int WineID = myArr[args.Position].WineId; var intent = new Intent(this, typeof(detailViewActivity)); intent.PutExtra("WineID", WineID); StartActivity(intent); }; ProgressIndicator.Hide(); } catch (Exception exe) { AlertDialog.Builder aler = new AlertDialog.Builder(this); aler.SetTitle("Sorry"); aler.SetMessage("We're under maintainence"); aler.SetNegativeButton("Ok", delegate { }); Dialog dialog = aler.Create(); dialog.Show(); } }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.web_mywebview); #region WebView var client = new ContentWebViewClient(); client.WebViewLocaitonChanged += (object sender, ContentWebViewClient.WebViewLocaitonChangedEventArgs e) => { Debug.WriteLine(e.CommandString); }; client.WebViewLoadCompleted += (object sender, ContentWebViewClient.WebViewLoadCompletedEventArgs e) => { RunOnUiThread(() => { AndHUD.Shared.Dismiss(this); }); }; MyWebView = FindViewById <WebView> (Resource.Id.web_mywebview_webview); // NOTICE : 先換成一般的 WebViewClient MyWebView.SetWebViewClient(client); //MyWebView.SetWebViewClient(new MyWebClient()); MyWebView.Settings.JavaScriptEnabled = true; MyWebView.Settings.UserAgentString = @"Android"; // 負責與頁面溝通 - WebView -> Native MyJSInterface myJSInterface = new MyJSInterface(this); MyWebView.AddJavascriptInterface(myJSInterface, "TP"); myJSInterface.CallFromPageReceived += delegate(object sender, MyJSInterface.CallFromPageReceivedEventArgs e) { Debug.WriteLine(e.Result); }; // 負責與頁面溝通 - Native -> WebView JavaScriptResult callResult = new JavaScriptResult(); callResult.JavaScriptResultReceived += (object sender, JavaScriptResult.JavaScriptResultReceivedEventArgs e) => { Debug.WriteLine(e.Result); }; // 載入一般網頁 //MyWebView.LoadUrl ("http://stackoverflow.com/"); // 載入以下程式碼進行互動 /* * MyWebView.LoadDataWithBaseURL ( * null * , @"<html> * <head> * <title>Local String</title> * <style type='text/css'>p{font-family : Verdana; color : purple }</style> * <script language='JavaScript'> * var lookup = '中文訊息' * function msg(){ window.location = 'callfrompage://Hi' } * </script> * </head> * <body><p>Hello World!</p><br /> * <button type='button' onclick='TP.CallFromPage(lookup)' text='Hi From Page'>Hi From Page</button> * </body> * </html>" * , "text/html" * , "utf-8" * , null); * */ #endregion #region EditText _InputMethodManager = (InputMethodManager)GetSystemService(Context.InputMethodService); TxtUrl = FindViewById <EditText> (Resource.Id.web_mywebview_txtUrl); TxtUrl.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { Debug.WriteLine(TxtUrl.Text + ":" + e.Text); }; #endregion BtnGo = FindViewById <Button> (Resource.Id.web_mywebview_btnGo); BtnGo.Click += (object sender, EventArgs e) => { //RunOnUiThread (() => { // MyWebView.EvaluateJavascript (@"msg();", callResult); //}); var url = TxtUrl.Text.Trim(); AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle(url); alert.SetMessage(""); alert.SetNegativeButton("取消", (senderAlert, args) => { }); alert.SetPositiveButton("確認", (senderAlert, args) => { RunOnUiThread( () => { AndHUD.Shared.Show(this, "Status Message", -1, MaskType.Clear); } ); MyWebView.LoadUrl(url); }); RunOnUiThread(() => { alert.Show(); }); // _InputMethodManager.HideSoftInputFromWindow( TxtUrl.WindowToken, HideSoftInputFlags.None); }; }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.Page); //update local tag cache m_sBaseDir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); this.UpdateTagCache(); m_pTags = FindViewById <EditText>(Resource.Id.txtTags); m_pSources = FindViewById <EditText>(Resource.Id.txtSource); EditText pSnippetContent = FindViewById <EditText>(Resource.Id.txtSnippetContent); EditText pSourceData = FindViewById <EditText>(Resource.Id.txtSourceData); Button pTagsButton = FindViewById <Button>(Resource.Id.btnTagsList); pTagsButton.Click += delegate { this.DisplayList("tags"); }; Button pSourceButton = FindViewById <Button>(Resource.Id.btnSourceList); pSourceButton.Click += delegate { this.DisplayList("sources"); }; Button pSubmitButton = FindViewById <Button>(Resource.Id.btnSubmit); pSubmitButton.Click += delegate { string sContent = pSnippetContent.Text; string sTags = m_pTags.Text + ",source:" + m_pSources.Text; // add meta tags //sContent = "<meta name='sourceTag' content='" + lblSourceName.Content + "'><meta name='source' content='" + txtSourceText.Text + "'>" + sContent; sContent = "<meta name='sourceTag' content='" + m_pSources.Text + "'><meta name='source' content='" + pSourceData.Text + "'>" + sContent; // make the xml request body string sBody = "<params>"; sBody += "<param name='sTagList'>" + sTags + "</param><param name='sSnippet'>" + Master.EncodeXML(sContent) + "</param>"; if (m_bEditing) { sBody += "<param name='sFileName'>" + m_sEditingSnippet + "</param>"; } sBody += "</params>"; string sResponse = ""; if (m_bEditing) { sResponse = WebCommunications.SendPostRequest("http://dwlapi.azurewebsites.net/api/reflection/KnowledgeBaseServer/KnowledgeBaseServer/KnowledgeServer/EditSnippet", sBody, true); } else { sResponse = WebCommunications.SendPostRequest("http://dwlapi.azurewebsites.net/api/reflection/KnowledgeBaseServer/KnowledgeBaseServer/KnowledgeServer/AddSnippet", sBody, true); } this.Finish(); }; Button pDeleteButton = FindViewById <Button>(Resource.Id.btnDelete); pDeleteButton.Click += delegate { if (!m_bEditing) { return; } // thanks to https://forums.xamarin.com/discussion/6096/how-show-confirmation-message-box-in-vs-2012 var pBuilder = new AlertDialog.Builder(this); pBuilder.SetMessage("Are you sure you want to delete this snippet?"); pBuilder.SetPositiveButton("Yes", (s, e) => { WebCommunications.SendGetRequest("http://dwlapi.azurewebsites.net/api/reflection/KnowledgeBaseServer/KnowledgeBaseServer/KnowledgeServer/DeleteSnippet?sfilename=" + m_sEditingSnippet, true); this.Finish(); }); pBuilder.SetNegativeButton("No", (s, e) => { return; }); pBuilder.Create().Show(); }; string sType = this.Intent.GetStringExtra("Type"); if (sType == "new") { m_bEditing = false; } else if (sType == "edit") { string sSnippetName = this.Intent.GetStringExtra("SnippetName"); string sSnippetSourceName = this.Intent.GetStringExtra("SourceName"); string sSnippetSourceText = this.Intent.GetStringExtra("SourceText"); string sSnippetTags = this.Intent.GetStringExtra("SnippetTags"); m_bEditing = true; m_sEditingSnippet = sSnippetName; // get the actual snippet content from the server string sSnippetContent = WebCommunications.SendGetRequest("http://dwlapi.azurewebsites.net/api/reflection/KnowledgeBaseServer/KnowledgeBaseServer/KnowledgeServer/GetSnippet?sfilename=" + sSnippetName, true); sSnippetContent = Master.CleanResponseForEditor(sSnippetContent); // remove the meta tags (since they are merely added back in on submit) Regex pRegex = new Regex(s_sMetaPattern); sSnippetContent = pRegex.Replace(sSnippetContent, ""); // fill fields pSnippetContent.Text = sSnippetContent; pSourceData.Text = sSnippetSourceText; m_pTags.Text = sSnippetTags; m_pSources.Text = sSnippetSourceName; this.Title = "Edit Snippet"; } }
private void Control_Click(object sender, EventArgs e) { Picker model = Element; if (_dialog != null) { return; } 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 = Android.Views.DescendantFocusability.BlockDescendants; picker.Value = model.SelectedIndex; } var layout = new LinearLayout(Context) { Orientation = Orientation.Vertical }; layout.AddView(picker); ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, true); var builder = new AlertDialog.Builder(Context); builder.SetView(layout); builder.SetTitle(model.Title ?? ""); builder.SetNegativeButton(customPicker.CancelButtonText ?? "Cancel", (s, a) => { ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); _dialog = null; }); builder.SetPositiveButton(customPicker.DoneButtonText ?? "Accept", (s, a) => { ElementController.SetValueFromRenderer(Picker.SelectedIndexProperty, picker.Value); // It is possible for the Content of the Page to be changed on SelectedIndexChanged. // In this case, the Element & Control will no longer exist. if (Element != null) { if (model.Items.Count > 0 && Element.SelectedIndex >= 0) { Control.Text = model.Items[Element.SelectedIndex]; } ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); } _dialog = null; }); _dialog = builder.Create(); _dialog.DismissEvent += (dSender, dArgs) => { ElementController?.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); _dialog?.Dispose(); _dialog = null; }; _dialog.Show(); }
void IPickerRenderer.OnClick() { Picker model = Element; 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); 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) => { ElementController.SetValueFromRenderer(Picker.SelectedIndexProperty, picker.Value); // It is possible for the Content of the Page to be changed on SelectedIndexChanged. // In this case, the Element & Control will no longer exist. if (Element != null) { if (model.Items.Count > 0 && Element.SelectedIndex >= 0) Control.Text = model.Items[Element.SelectedIndex]; ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); } _dialog = null; }); _dialog = builder.Create(); _dialog.DismissEvent += (sender, args) => { ElementController?.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); }; _dialog.Show(); }
protected override Dialog OnCreateDialog(int id) { switch (id) { case DIALOG_YES_NO_MESSAGE: { var builder = new AlertDialog.Builder(this); builder.SetIconAttribute(Android.Resource.Attribute.AlertDialogIcon); builder.SetTitle(Resource.String.alert_dialog_two_buttons_title); builder.SetPositiveButton(Resource.String.alert_dialog_ok, OkClicked); builder.SetNegativeButton(Resource.String.alert_dialog_cancel, CancelClicked); return(builder.Create()); } case DIALOG_YES_NO_OLD_SCHOOL_MESSAGE: { var builder = new AlertDialog.Builder(this, Android.App.AlertDialog.ThemeTraditional); builder.SetIconAttribute(Android.Resource.Attribute.AlertDialogIcon); builder.SetTitle(Resource.String.alert_dialog_two_buttons_title); builder.SetPositiveButton(Resource.String.alert_dialog_ok, OkClicked); builder.SetNegativeButton(Resource.String.alert_dialog_cancel, CancelClicked); return(builder.Create()); } case DIALOG_YES_NO_HOLO_LIGHT_MESSAGE: { var builder = new AlertDialog.Builder(this, Android.App.AlertDialog.ThemeHoloLight); builder.SetIconAttribute(Android.Resource.Attribute.AlertDialogIcon); builder.SetTitle(Resource.String.alert_dialog_two_buttons_title); builder.SetPositiveButton(Resource.String.alert_dialog_ok, OkClicked); builder.SetNegativeButton(Resource.String.alert_dialog_cancel, CancelClicked); return(builder.Create()); } case DIALOG_YES_NO_LONG_MESSAGE: { var builder = new AlertDialog.Builder(this); builder.SetIconAttribute(Android.Resource.Attribute.AlertDialogIcon); builder.SetTitle(Resource.String.alert_dialog_two_buttons_msg); builder.SetMessage(Resource.String.alert_dialog_two_buttons_msg); builder.SetPositiveButton(Resource.String.alert_dialog_ok, OkClicked); builder.SetNegativeButton(Resource.String.alert_dialog_cancel, CancelClicked); builder.SetNeutralButton(Resource.String.alert_dialog_something, NeutralClicked); return(builder.Create()); } case DIALOG_YES_NO_ULTRA_LONG_MESSAGE: { var builder = new AlertDialog.Builder(this); builder.SetIconAttribute(Android.Resource.Attribute.AlertDialogIcon); builder.SetTitle(Resource.String.alert_dialog_two_buttons_msg); builder.SetMessage(Resource.String.alert_dialog_two_buttons2ultra_msg); builder.SetPositiveButton(Resource.String.alert_dialog_ok, OkClicked); builder.SetNegativeButton(Resource.String.alert_dialog_cancel, CancelClicked); builder.SetNeutralButton(Resource.String.alert_dialog_something, NeutralClicked); return(builder.Create()); } case DIALOG_LIST: { var builder = new AlertDialog.Builder(this); builder.SetTitle(Resource.String.select_dialog); builder.SetItems(Resource.Array.select_dialog_items, ListClicked); return(builder.Create()); } case DIALOG_PROGRESS: { progress_dialog = new ProgressDialog(this); progress_dialog.SetIconAttribute(Android.Resource.Attribute.AlertDialogIcon); progress_dialog.SetTitle(Resource.String.select_dialog); progress_dialog.SetProgressStyle(ProgressDialogStyle.Horizontal); progress_dialog.Max = MAX_PROGRESS; progress_dialog.SetButton(-1, GetText(Resource.String.alert_dialog_ok), OkClicked); progress_dialog.SetButton(-2, GetText(Resource.String.alert_dialog_cancel), CancelClicked); return(progress_dialog); } case DIALOG_SINGLE_CHOICE: { var builder = new AlertDialog.Builder(this); builder.SetIconAttribute(Android.Resource.Attribute.AlertDialogIcon); builder.SetTitle(Resource.String.alert_dialog_single_choice); builder.SetSingleChoiceItems(Resource.Array.select_dialog_items2, 0, ListClicked); builder.SetPositiveButton(Resource.String.alert_dialog_ok, OkClicked); builder.SetNegativeButton(Resource.String.alert_dialog_cancel, CancelClicked); return(builder.Create()); } case DIALOG_MULTIPLE_CHOICE: { var builder = new AlertDialog.Builder(this); builder.SetIcon(Resource.Drawable.ic_popup_reminder); builder.SetTitle(Resource.String.alert_dialog_multi_choice); builder.SetMultiChoiceItems(Resource.Array.select_dialog_items3, new bool[] { false, true, false, true, false, false, false }, MultiListClicked); builder.SetPositiveButton(Resource.String.alert_dialog_ok, OkClicked); builder.SetNegativeButton(Resource.String.alert_dialog_cancel, CancelClicked); return(builder.Create()); } case DIALOG_MULTIPLE_CHOICE_CURSOR: { var projection = new string[] { ContactsContract.Contacts.InterfaceConsts.Id, ContactsContract.Contacts.InterfaceConsts.DisplayName, ContactsContract.Contacts.InterfaceConsts.SendToVoicemail }; var cursor = ManagedQuery(ContactsContract.Contacts.ContentUri, projection, null, null, null); var builder = new AlertDialog.Builder(this); builder.SetIcon(Resource.Drawable.ic_popup_reminder); builder.SetTitle(Resource.String.alert_dialog_multi_choice_cursor); builder.SetMultiChoiceItems(cursor, ContactsContract.Contacts.InterfaceConsts.SendToVoicemail, ContactsContract.Contacts.InterfaceConsts.DisplayName, MultiListClicked); return(builder.Create()); } case DIALOG_TEXT_ENTRY: { // This example shows how to add a custom layout to an AlertDialog var factory = LayoutInflater.From(this); var text_entry_view = factory.Inflate(Resource.Layout.alert_dialog_text_entry, null); var builder = new AlertDialog.Builder(this); builder.SetIconAttribute(Android.Resource.Attribute.AlertDialogIcon); builder.SetTitle(Resource.String.alert_dialog_text_entry); builder.SetView(text_entry_view); builder.SetPositiveButton(Resource.String.alert_dialog_ok, OkClicked); builder.SetNegativeButton(Resource.String.alert_dialog_cancel, CancelClicked); return(builder.Create()); } } return(null); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.BookDetail); string updateBookId = ""; Button borrowButton = FindViewById <Button>(Resource.Id.borrow1); Button collectionButton = FindViewById <Button>(Resource.Id.collection1); TabHost tab = FindViewById <TabHost>(Resource.Id.tabHost123); TextView bookSummary = FindViewById <TextView>(Resource.Id.textView_BookSummary); //内容概要 TextView bookCatalog = FindViewById <TextView>(Resource.Id.textView_BookCatalog); //本书目录 TextView bookClassId = FindViewById <TextView>(Resource.Id.textView_BookClassId); TextView bookPrice = FindViewById <TextView>(Resource.Id.textView_BookPrice); TextView bookPress = FindViewById <TextView>(Resource.Id.textView_BookPress); TextView bookClassification = FindViewById <TextView>(Resource.Id.textView_BookClassification); TextView bookAuthor = FindViewById <TextView>(Resource.Id.bookDetailAuthor); TextView bookName = FindViewById <TextView>(Resource.Id.bookDetailBookname); bool totalbooknumber2 = false; bool renewdays3 = false; bool notrenewdays4 = false; bool returncheck5 = false; ISharedPreferences LoginSP = GetSharedPreferences("LoginData", FileCreationMode.Private); string PhoneNum = LoginSP.GetString("PhoneNum", null); //获取电话号码 string thebookClassId = Intent.GetStringExtra("BookClassId"); string PersonTotalBookResult = PersonalTotalBookData.Post("http://115.159.145.115/PersonalTotalBook.php/", PhoneNum); //检查个人借书总数是否超过规定 string personaltotalbooknumber = PersonTotalBookResult; string RenewDaysResult = RenewDaysData.Post("http://115.159.145.115/RenewDays.php/", PhoneNum); //检查已续借的书是否过期 string renewdays = RenewDaysResult; string NotRenewDaysResult = NotRenewDaysData.Post("http://115.159.145.115/NotRenewDays.php/", PhoneNum); //检查未续借的书是否过期 string notrenewdays = NotRenewDaysResult; string result = BookDetailData.Post("http://115.159.145.115/BookDetail.php/", thebookClassId); var book = JsonConvert.DeserializeObject <BookClass>(result); //本类书详情 string result1 = BookDetailData.Post("http://115.159.145.115/ReturnCheck.php/", thebookClassId); var returncheck = JsonConvert.DeserializeObject <List <ReturnCheck> >(result1); //读借书信息 if (personaltotalbooknumber != null) { int thetotalbooknumber = 0; int.TryParse(personaltotalbooknumber, out thetotalbooknumber); if (thetotalbooknumber >= 0 && thetotalbooknumber < 10) { //符合规定,可以借书 totalbooknumber2 = true; } else { //不能借书 totalbooknumber2 = false; } } if (renewdays != null) { int therenewdays = 0; int.TryParse(renewdays, out therenewdays); if (therenewdays >= 0 && therenewdays <= 20) { //符合规定,可以借书 renewdays3 = true; } else { //超过续借日期,不能借书 renewdays3 = false; } } else { //可以借书 renewdays3 = true; } if (notrenewdays != null) { int thenotrenewdays = 0; int.TryParse(notrenewdays, out thenotrenewdays); if (thenotrenewdays >= 0 && thenotrenewdays <= 10) { //可以借书 notrenewdays4 = true; } else { //超期未还,不能借书 notrenewdays4 = false; } } else { //可以借书 notrenewdays4 = true; } int judgePhoneNum = 0; int judge = 1; //判断该类书是否被借完 int judgeRenew = 0; //判断是本书是否续借 if (returncheck.Count == 0) { //无法传BookID string QueryIdResult = BookDetailData.Post("http://115.159.145.115/QueryId.php/", thebookClassId); var queryid = JsonConvert.DeserializeObject <List <QueryId> >(QueryIdResult); foreach (QueryId b in queryid) { updateBookId = b.BookId; } returncheck5 = true; } else { foreach (ReturnCheck a in returncheck) { if (a.ReturnFlag == "1") { updateBookId = a.BookId; //可以借书 returncheck5 = true; } else if (a.PhoneNum == PhoneNum && a.ReturnFlag == "0") { if (a.IfRenew == "0") { judgeRenew = 0; //本书没有被续借 } else { judgeRenew = 1; //本书已经被续借 } updateBookId = a.BookId; returncheck5 = false; judgePhoneNum = 1; //还书或续借 } else { //又不可以借,又不可以还 //该类书已经被借完 judge = 0; } } } bookAuthor.Text = book.BookAuthor; //标题:作者 bookName.Text = book.BookName; //标题:书名 bookSummary.Text = book.BookSummary; //Tab1:内容概要 bookCatalog.Text = book.BookCatalog; //Tab2:本书目录 bookClassId.Text = "ISBN :" + book.BookClassId; bookPrice.Text = "价 格:" + book.BookPrice; bookPress.Text = "出版社:" + book.BookPress; bookClassification.Text = "分 类:" + book.BookClassification; Picasso.With(this).Load(book.ImageUrl).Into(FindViewById <ImageView>(Resource.Id.imageView_bookImage)); tab.Setup(); TabHost.TabSpec spec1 = tab.NewTabSpec("tab1"); spec1.SetContent(Resource.Id.layoutBookSummary); spec1.SetIndicator("内容概要"); TabHost.TabSpec spec2 = tab.NewTabSpec("tab2"); spec2.SetContent(Resource.Id.layoutBookCatalog); spec2.SetIndicator("本书目录"); TabHost.TabSpec spec3 = tab.NewTabSpec("tab3"); spec3.SetContent(Resource.Id.layoutIntroduction); spec3.SetIndicator("发行简介"); tab.AddTab(spec1); tab.AddTab(spec2); tab.AddTab(spec3); if (returncheck5 == false && judgePhoneNum == 1) { borrowButton.Text = "还书"; borrowButton.Click += (s, e) => { var Dialog = new AlertDialog.Builder(this); Dialog.SetMessage("确认要还此书?"); Dialog.SetNeutralButton("确认", delegate { ThisBook thisbook = new ThisBook(); thisbook.BookId = updateBookId; thisbook.PhoneNum = PhoneNum; var ReturnJson = JsonConvert.SerializeObject(thisbook); Intent intent = new Intent(this, typeof(ReturnReader)); intent.PutExtra("ReturnBook", "[" + ReturnJson + "]"); StartActivity(intent); }); Dialog.SetNegativeButton("取消", delegate { }); Dialog.Show(); }; if (judgeRenew == 0) //没有被续借 { collectionButton.Text = "续借"; collectionButton.Click += (s, e) => { var Dialog = new AlertDialog.Builder(this); Dialog.SetMessage("确认续借此书?"); Dialog.SetNeutralButton("确认", delegate { string theupdatesuccess = UpdateRenewData.Post("http://115.159.145.115/Renew.php/", updateBookId, PhoneNum); if (theupdatesuccess == "success") { Toast.MakeText(this, "续借成功!", ToastLength.Short).Show(); collectionButton.Enabled = false; } else { Toast.MakeText(this, "抱歉,续借失败!", ToastLength.Short).Show(); } }); Dialog.SetNegativeButton("取消", delegate { }); Dialog.Show(); }; } else if (judgeRenew == 1) { collectionButton.Text = "续借"; collectionButton.Enabled = false; Toast.MakeText(this, "您已续借此书,无法再次续借!", ToastLength.Short).Show(); } } else if (judge == 1 && totalbooknumber2 == true && renewdays3 == true && notrenewdays4 == true && returncheck5 == true) { borrowButton.Text = "借书"; borrowButton.Click += (s, e) => { var Dialog = new AlertDialog.Builder(this); Dialog.SetMessage("确认借阅此书?"); Dialog.SetNeutralButton("确认", delegate { ThisBook thisbook = new ThisBook(); thisbook.BookId = updateBookId; thisbook.PhoneNum = PhoneNum; var ReturnJson = JsonConvert.SerializeObject(thisbook); Intent ActLogin = new Intent(this, typeof(BorrowReader)); ActLogin.PutExtra("BorrowInfo", "[" + ReturnJson + "]"); StartActivity(ActLogin); }); Dialog.SetNegativeButton("取消", delegate { }); Dialog.Show(); }; collectionButton.Text = "加入书篮"; if (AddToBookBasketData.Post("http://115.159.145.115/IfInBookBasket.php/", PhoneNum, book.BookClassId) != "NotIn") { collectionButton.Enabled = false; } collectionButton.Click += (s, e) => { var Dialog = new AlertDialog.Builder(this); Dialog.SetMessage("确认将此书加入书栏?"); Dialog.SetNeutralButton("确认", delegate { string res = AddToBookBasketData.Post("http://115.159.145.115/AddToBookBasket.php", PhoneNum, book.BookClassId); if (res == "Success") { Toast.MakeText(this, "成功加入书栏!", ToastLength.Short).Show(); collectionButton.Enabled = false; } }); Dialog.SetNegativeButton("取消", delegate { }); Dialog.Show(); }; } else if (judge == 0) { borrowButton.Text = "借书"; collectionButton.Text = "加入书篮"; borrowButton.Enabled = false; collectionButton.Enabled = false; Toast.MakeText(this, "抱歉,此类书已经被借完!您无法借阅此书!", ToastLength.Short).Show(); } else if (totalbooknumber2 == false) { borrowButton.Text = "借书"; collectionButton.Text = "加入书篮"; borrowButton.Enabled = false; collectionButton.Enabled = false; Toast.MakeText(this, "抱歉,您的借阅书本数量已满十本!您无法借阅此书!", ToastLength.Short).Show(); } else if (renewdays3 == false) { borrowButton.Text = "借书"; collectionButton.Text = "加入书篮"; borrowButton.Enabled = false; collectionButton.Enabled = false; Toast.MakeText(this, "抱歉,您有续借图书超期未还!您无法借阅此书!", ToastLength.Short).Show(); } else if (notrenewdays4 == false) { borrowButton.Text = "借书"; collectionButton.Text = "加入书篮"; borrowButton.Enabled = false; collectionButton.Enabled = false; Toast.MakeText(this, "抱歉,您有借阅图书超期未还!您无法借阅此书!", ToastLength.Short).Show(); } }
public async Task <string> GetFileOrDirectoryAsync(String dir) { File dirFile = new File(dir); while (!dirFile.Exists() || !dirFile.IsDirectory) { dir = dirFile.Parent; dirFile = new File(dir); } try { dir = new File(dir).CanonicalPath; } catch (IOException ioe) { return(_result); } _mDir = dir; _mSubdirs = GetDirectories(dir); AlertDialog.Builder dialogBuilder = CreateDirectoryChooserDialog(dir, _mSubdirs, (sender, args) => { String mDirOld = _mDir; String sel = "" + ((AlertDialog)sender).ListView.Adapter.GetItem(args.Which); if (sel[sel.Length - 1] == '/') { sel = sel.Substring(0, sel.Length - 1); } if (sel.Equals("Atras...")) { _mDir = _mDir.Substring(0, _mDir.LastIndexOf("/")); if ("".Equals(_mDir)) { _mDir = "/"; } } else { _mDir += "/" + sel; } _selectedFileName = DefaultFileName; if ((new File(_mDir).IsFile)) { _mDir = mDirOld; _selectedFileName = sel; } UpdateDirectory(); }); dialogBuilder.SetPositiveButton("OK", (sender, args) => { { if (_selectType == _fileOpen || _selectType == _fileSave) { _selectedFileName = _inputText.Text + ""; _result = _mDir + "/" + _selectedFileName; _autoResetEvent.Set(); } else { _result = _mDir; _autoResetEvent.Set(); } } }); dialogBuilder.SetNegativeButton("Cancelar", (sender, args) => { }); _dirsDialog = dialogBuilder.Create(); _dirsDialog.CancelEvent += (sender, args) => { _autoResetEvent.Set(); }; _dirsDialog.DismissEvent += (sender, args) => { _autoResetEvent.Set(); }; _autoResetEvent = new AutoResetEvent(false); _dirsDialog.Show(); await Task.Run(() => { _autoResetEvent.WaitOne(); }); return(_result); }
void OnClick() { Picker model = Element; 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); ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, true); var builder = new AlertDialog.Builder(Context); builder.SetView(layout); builder.SetTitle(model.Title ?? ""); builder.SetNegativeButton(Platform.Resource_String_Cancel(), (s, a) => { ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); // It is possible for the Content of the Page to be changed when Focus is changed. // In this case, we'll lose our Control. Control?.ClearFocus(); _dialog = null; }); builder.SetPositiveButton(Platform.Resource_String_OK(), (s, a) => { ElementController.SetValueFromRenderer(Picker.SelectedIndexProperty, picker.Value); // It is possible for the Content of the Page to be changed on SelectedIndexChanged. // In this case, the Element & Control will no longer exist. if (Element != null) { if (model.Items.Count > 0 && Element.SelectedIndex >= 0) { Control.Text = model.Items[Element.SelectedIndex]; } ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); // It is also possible for the Content of the Page to be changed when Focus is changed. // In this case, we'll lose our Control. Control?.ClearFocus(); } _dialog = null; }); _dialog = builder.Create(); _dialog.DismissEvent += (sender, args) => { ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); }; _dialog.Show(); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Group); Button butGroupNew = FindViewById <Button> (Resource.Id.btnJoinGroup); butGroupNew.Click += delegate { Intent GroupNewIntent = new Intent(this, typeof(GroupNewActivity)); StartActivityForResult(GroupNewIntent, ACTIVITY_FOR_CHANGEGROUP); }; Button butGroupClose = FindViewById <Button> (Resource.Id.btnCloseGroup); butGroupClose.Click += delegate { var builder = new AlertDialog.Builder(this); builder.SetTitle("Warning"); builder.SetMessage("Do you want to close this group?"); builder.SetPositiveButton("Yes", (sender, args) => { _progDlg = ProgressDialog.Show(this, "", GetString(Resource.String.msg_wait), true, true); _progDlg.CancelEvent += (object sender1, EventArgs e) => { }; WebService.doCloseGroup(this, _groupList[_selGroupId].groupId); }); builder.SetNegativeButton("No", (sender, args) => { }); builder.SetCancelable(false); builder.Show(); }; Button butAcceptUser = FindViewById <Button> (Resource.Id.btnAccept); butAcceptUser.Click += delegate { _progDlg = ProgressDialog.Show(this, "", GetString(Resource.String.msg_wait), true, true); _progDlg.CancelEvent += (object sender, EventArgs e) => { }; WebService.doAcceptUser(this, _groupMemberList[_selMemberId].memberId, _groupList[_selGroupId].groupId); }; Button butKickUser = FindViewById <Button> (Resource.Id.btnKick); butKickUser.Click += delegate { _progDlg = ProgressDialog.Show(this, "", GetString(Resource.String.msg_wait), true, true); _progDlg.CancelEvent += (object sender, EventArgs e) => { }; WebService.doKickUser(this, _groupMemberList[_selMemberId].memberId, _groupList[_selGroupId].groupId); }; Button btnChangePoints = FindViewById <Button> (Resource.Id.btnAddSubPoints); btnChangePoints.Click += delegate { EditText txtPoints = FindViewById <EditText>(Resource.Id.txtNewPoints); if (String.IsNullOrEmpty(txtPoints.Text)) { Toast.MakeText(this, "Please input points to change", ToastLength.Short); return; } _progDlg = ProgressDialog.Show(this, "", GetString(Resource.String.msg_wait), true, true); _progDlg.CancelEvent += (object sender, EventArgs e) => { }; WebService.changeMemberPoints(this, _groupMemberList[_selMemberId].memberId, int.Parse(txtPoints.Text)); txtPoints.Text = ""; }; LinearLayout butHome = FindViewById <LinearLayout>(Resource.Id.linearBtnHome); LinearLayout butActivity = FindViewById <LinearLayout>(Resource.Id.linearBtnActivity); LinearLayout butTask = FindViewById <LinearLayout>(Resource.Id.linearBtnTask); LinearLayout butNotification = FindViewById <LinearLayout>(Resource.Id.linearBtnNotify); butHome.Click += delegate { Intent homeIntent = new Intent(this, typeof(HomeActivity)); StartActivity(homeIntent); Finish(); }; butActivity.Click += delegate { Intent activityIntent = new Intent(this, typeof(ActivityActivity)); StartActivity(activityIntent); Finish(); }; butTask.Click += delegate { Intent taskIntent = new Intent(this, typeof(TaskActivity)); StartActivity(taskIntent); Finish(); }; butNotification.Click += delegate { Intent notifyIntent = new Intent(this, typeof(NotifyActivity)); StartActivity(notifyIntent); Finish(); }; updateUserInfo(); changeButtonEnable(0); runBackground(); Global.HideKeyboard(this, InputMethodService); }
public async Task <bool> CheckEventLocationPermission() { try { Activity activity = MainActivity.ThisActivity; LocationManager locationManager = (LocationManager)activity.GetSystemService(Context.LocationService); bool isGPSEnabled = locationManager.IsProviderEnabled(LocationManager.GpsProvider); //If Version greater than Marshallow need to give run time permission if (isGPSEnabled) { if (Build.VERSION.SdkInt >= BuildVersionCodes.M) { if (ContextCompat.CheckSelfPermission(activity, Manifest.Permission.AccessFineLocation) == (int)Permission.Granted) { // We have been given permission. return(true); } else { // If necessary display rationale & request. if (ActivityCompat.ShouldShowRequestPermissionRationale(activity, Manifest.Permission.AccessFineLocation)) { // Provide an additional rationale to the user if the permission was not granted // and the user would benefit from additional context for the use of the permission. // For example if the user has previously denied the permission. //Log.Info("Location", "Displaying Location permission rationale to provide additional context."); var requiredPermissions = new String[] { Manifest.Permission.AccessFineLocation }; ActivityCompat.RequestPermissions(activity, requiredPermissions, 200); return(false); } else { //Show alertbox to prompt user to enable location services in app level AlertDialog.Builder alert = new AlertDialog.Builder(activity); alert.SetTitle("Location Permission"); alert.SetCancelable(false); alert.SetMessage("App needs location permission to access your current location"); alert.SetPositiveButton("OK", (senderAlert, args) => { MainActivity.FormsContext.StartActivity(new Intent(Android.Provider.Settings.ActionApplicationDetailsSettings, Android.Net.Uri.Parse("package:com.xamarinlife.locationpermissions"))); }); alert.SetNegativeButton("Cancel", (senderAlert, args) => { //MessagingCenter.Send<object>("EVENTLOCATION", "REJECTED"); }); Dialog dialog = alert.Create(); dialog.Show(); return(false); } } } //Less than Marshmallow version so we can request directly else { ActivityCompat.RequestPermissions(activity, new String[] { Manifest.Permission.AccessFineLocation }, 200); return(false); } } else { //show popup to redirect to settings page to enable GPS AlertDialog.Builder alert = new AlertDialog.Builder(activity); alert.SetTitle("GPS "); alert.SetCancelable(false); alert.SetMessage("GPS is disabled. Please enable GPS to access full feature."); alert.SetPositiveButton("OK", (senderAlert, args) => { MainActivity.FormsContext.StartActivity(new Intent(Android.Provider.Settings.ActionSettings)); }); alert.SetNegativeButton("Cancel", (senderAlert, args) => { //MessagingCenter.Send<object>("EVENTLOCATION", "REJECTED"); }); Dialog dialog = alert.Create(); dialog.Show(); return(false); } } catch (Exception ex) { throw ex; } }
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); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); // Get our UI controls from the loaded layout: EditText phoneNumberText = FindViewById <EditText>(Resource.Id.PhoneNumberText); Button translateButton = FindViewById <Button>(Resource.Id.TranslateButton); Button callButton = FindViewById <Button>(Resource.Id.CallButton); Button callHistoryButton = FindViewById <Button>(Resource.Id.CallHistoryButton); // Disable the "Call" button callButton.Enabled = false; // Add code to translate number string translatedNumber = string.Empty; translateButton.Click += (object sender, EventArgs e) => { // Translate user's alphanumeric phone number to numeric translatedNumber = Core.PhonewordTranslator.ToNumber(phoneNumberText.Text); if (String.IsNullOrWhiteSpace(translatedNumber)) { callButton.Text = "Call"; callButton.Enabled = false; } else { callButton.Text = "Call " + translatedNumber; callButton.Enabled = true; } }; callButton.Click += (object sender, EventArgs e) => { // On "Call" button click, try to dial phone number. var callDialog = new AlertDialog.Builder(this); callDialog.SetMessage("Call " + translatedNumber + "?"); callDialog.SetNeutralButton("Call", delegate { // add dialed number to list of called numbers. phoneNumbers.Add(translatedNumber); // enable the Call History button callHistoryButton.Enabled = true; // Create intent to dial phone var callIntent = new Intent(Intent.ActionCall); callIntent.SetData(Android.Net.Uri.Parse("tel:" + translatedNumber)); StartActivity(callIntent); }); callDialog.SetNegativeButton("Cancel", delegate { }); // Show the alert dialog to the user and wait for response. callDialog.Show(); }; callHistoryButton.Click += (sender, e) => { var intent = new Intent(this, typeof(CallHistoryActivity)); intent.PutStringArrayListExtra("phone_numbers", phoneNumbers); StartActivity(intent); }; }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); var messageList = FindViewById <ListView>(Resource.Id.msgList); adapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleListItem1); messageList.Adapter = adapter; var progressBar = FindViewById <ProgressBar>(Resource.Id.downloadProgressBar); progressBar.Max = 100; var datePicker = FindViewById <DatePicker>(Resource.Id.downloadDatePicker); var button = FindViewById <Button>(Resource.Id.downloadButton); button.Click += async(object sender, EventArgs e) => { var cm = GetSystemService(ConnectivityService) as ConnectivityManager; if (cm?.ActiveNetworkInfo.Type != ConnectivityType.Wifi) { var builder = new AlertDialog.Builder(this); builder.SetMessage("Connect without wifi?"); builder.SetNegativeButton("Cancel", (obj, x) => { }); builder.SetPositiveButton("Ok", async(obj, which) => { await StartBatchDownload(); }); builder.Show(); } else { await StartBatchDownload(); } }; Task StartBatchDownload() { return(Task.Run(() => { var savePath = GetSavePath(); AddressBuilder.Date = datePicker.DateTime; var addrs = AddressBuilder.Load(Assets.Open("PodAddress.xml")); var urls = AddressBuilder.GetEffectiveAddresses(addrs); List <string> failedList = new List <string>(); failedList.AddRange(BatchDownloader.DownloadFromUrls(savePath, urls, DownloadProgressHandler)); RunOnUiThread(() => { failedList .Select(msg => "failed url: " + msg) .ToList() .ForEach(msg => { Log.Info(typeof(MainActivity).ToString(), msg); adapter.Add(msg); }); adapter.Add("Download complete"); adapter.NotifyDataSetChanged(); Toast.MakeText(this, "Download complete", ToastLength.Long).Show(); }); })); } void DownloadProgressHandler(object sender, DownloadProgressChangedEventArgs e) { progressBar.SetProgress(e.ProgressPercentage, true); } }
void basesList_ItemLongClick(object sender, AdapterView.ItemLongClickEventArgs e) { if (e.Position < _manager.Infobases.Length) { using (var builder = new AlertDialog.Builder(Activity)) { var infobase = _manager.Infobases[e.Position]; builder.SetTitle(infobase.Name); var ll = new LinearLayout(Activity) { Orientation = Orientation.Vertical }; ll.SetPadding(10, 5, 10, 5); builder.SetView(ll); ll.AddView(new TextView(Activity) { Text = D.URL }); var editUrl = new EditText(Activity) { Text = infobase.BaseUrl }; editUrl.SetSingleLine(); ll.AddView(editUrl); ll.AddView(new TextView(Activity) { Text = D.APPLICATION }); var editApplication = new EditText(Activity) { Text = infobase.ApplicationString }; editApplication.SetSingleLine(); ll.AddView(editApplication); ll.AddView(new TextView(Activity) { Text = D.FTP_PORT }); var editFtpPort = new EditText(Activity) { Text = infobase.FtpPort }; editFtpPort.SetSingleLine(); ll.AddView(editFtpPort); builder.SetPositiveButton(D.OK, (s, args) => { infobase.BaseUrl = editUrl.Text; infobase.ApplicationString = editApplication.Text; infobase.FtpPort = editFtpPort.Text; _manager.SaveInfobases(); LoadList(); }); builder.SetNegativeButton(D.CANCEL, (s, args) => { }); builder.SetNeutralButton(D.DELETE, (s, args) => DeleteInfobase(e.Position)); builder.Show(); } } }
public Task <string> DisplayPromptAync(string title = null, string description = null, string text = null, string okButtonText = null, string cancelButtonText = null, bool numericKeyboard = false, bool autofocus = true, bool password = false) { var activity = (MainActivity)CrossCurrentActivity.Current.Activity; if (activity == null) { return(Task.FromResult <string>(null)); } var alertBuilder = new AlertDialog.Builder(activity); alertBuilder.SetTitle(title); alertBuilder.SetMessage(description); var input = new EditText(activity) { InputType = InputTypes.ClassText }; if (text == null) { text = string.Empty; } if (numericKeyboard) { input.InputType = InputTypes.ClassNumber | InputTypes.NumberFlagDecimal | InputTypes.NumberFlagSigned; #pragma warning disable CS0618 // Type or member is obsolete input.KeyListener = DigitsKeyListener.GetInstance(false, false); #pragma warning restore CS0618 // Type or member is obsolete } if (password) { input.InputType = InputTypes.TextVariationPassword | InputTypes.ClassText; } input.ImeOptions = input.ImeOptions | (ImeAction)ImeFlags.NoPersonalizedLearning | (ImeAction)ImeFlags.NoExtractUi; input.Text = text; input.SetSelection(text.Length); var container = new FrameLayout(activity); var lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent); lp.SetMargins(25, 0, 25, 0); input.LayoutParameters = lp; container.AddView(input); alertBuilder.SetView(container); okButtonText = okButtonText ?? AppResources.Ok; cancelButtonText = cancelButtonText ?? AppResources.Cancel; var result = new TaskCompletionSource <string>(); alertBuilder.SetPositiveButton(okButtonText, (sender, args) => result.TrySetResult(input.Text ?? string.Empty)); alertBuilder.SetNegativeButton(cancelButtonText, (sender, args) => result.TrySetResult(null)); var alert = alertBuilder.Create(); alert.Window.SetSoftInputMode(Android.Views.SoftInput.StateVisible); alert.Show(); if (autofocus) { input.RequestFocus(); } return(result.Task); }
void HandleItemClick(object sender, AdapterView.ItemClickEventArgs e) { var item = adapter [e.Position]; var alert = new AlertDialog.Builder(this); alert.SetIcon(Resource.Drawable.ic_launcher); alert.SetTitle(Resource.String.steps_cap); var view = LayoutInflater.Inflate(Resource.Layout.step_entry, null); var stepsEdit = view.FindViewById <EditText> (Resource.Id.step_count); stepsEdit.Text = item.Steps.ToString(); alert.SetView(view); alert.SetPositiveButton(Resource.String.ok, (object sender2, DialogClickEventArgs e2) => { //so now we want to see where we were previously, and where they //want to set it. We will update the database entry, //update total steps in settings, and action bar title //which will also invalidate our share options! //if they set it to a negative number do not allow it. var newCount = -1; if (!Int32.TryParse(stepsEdit.Text, out newCount)) { return; } if (newCount < 0) { return; } var diff = newCount - item.Steps; //update total steps even if negative as it will never go to 0 //also update steps before today so home screen is correct and doesn't change Settings.TotalSteps += diff; Settings.StepsBeforeToday += diff; if (spinnerAdapter != null) { var last7 = DateTime.Today.AddDays(-6); var last30 = DateTime.Today.AddDays(-30); if (item.Date >= last7) { weekSteps += diff; monthSteps += diff; } else if (item.Date >= last30) { monthSteps += diff; } } item.Steps = newCount; Database.StepEntryManager.SaveStepEntry(item); //update UI RunOnUiThread(() => { adapter.NotifyDataSetChanged(); SetActionBar(); }); }); //we are lucky here as cancel is translated by android :) alert.SetNegativeButton(Android.Resource.String.Cancel, delegate { //do nothing here. }); alert.Show(); }
public override Task <int?> ShowDialogAsync( object body, IEnumerable <object> buttons, string caption = null, int defaultAcceptButtonIndex = -1, DialogController dialogController = null) { Context context = ResolveContext(); AlertDialog.Builder builder = CreateAlertDialogBuilder(context, DialogStyle); if (dialogController != null && !dialogController.Cancellable) { builder.SetCancelable(false); } if (!string.IsNullOrWhiteSpace(caption)) { var stringParserService = Dependency.Resolve <IStringParserService>(); var parsedText = stringParserService.Parse(caption); builder.SetTitle(parsedText); } var bodyView = body as View; if (bodyView != null) { builder.SetView(bodyView); } else { var sequence = body as ICharSequence; if (sequence != null) { builder.SetMessage(sequence); } else { string bodyText = body?.ToString(); if (!string.IsNullOrWhiteSpace(bodyText)) { var stringParserService = Dependency.Resolve <IStringParserService>(); var parsedText = stringParserService.Parse(bodyText); ; builder.SetMessage(parsedText); } } } List <string> labels = null; int labelCount = 0; if (buttons != null) { labels = new List <string>(); foreach (var button in buttons) { string buttonText = button.ToString(); labels.Add(buttonText); } labelCount = labels.Count; } var resultSource = new TaskCompletionSource <int?>(); if (labelCount >= 2) { builder.SetNegativeButton(labels[0], (dialog, whichButton) => { resultSource.TrySetResult(0); }); for (int i = 1; i < labelCount - 1; i++) { int iClosureCopy = i; builder.SetNeutralButton(labels[i], (dialog, whichButton) => { resultSource.TrySetResult(iClosureCopy); }); } builder.SetPositiveButton(labels[labelCount - 1], (dialog, whichButton) => { int selectedIndex = labelCount - 1; resultSource.TrySetResult(selectedIndex); }); } else { if (labelCount == 1) { string buttonLabel = labels[0]; builder.SetPositiveButton(buttonLabel, (dialog, whichButton) => { resultSource.TrySetResult(0); }); } } builder.NothingSelected += (sender, e) => resultSource.TrySetResult(-1); Android.App.Application.SynchronizationContext.Post((object state) => { try { Interlocked.Increment(ref openDialogCount); AlertDialog alertDialog = builder.Show(); alertDialog.SetCanceledOnTouchOutside(false); var dialogStyles = dialogController?.DialogStyles; if (dialogStyles.HasValue) { var styles = dialogStyles.Value; var lp = new WindowManagerLayoutParams(); Window window = alertDialog.Window; lp.CopyFrom(window.Attributes); var stretchHorizontal = (styles & DialogStyles.StretchHorizontal) == DialogStyles.StretchHorizontal; var stretchVertical = (styles & DialogStyles.StretchVertical) == DialogStyles.StretchVertical; lp.Width = stretchHorizontal ? ViewGroup.LayoutParams.MatchParent : lp.Width; lp.Height = stretchVertical ? ViewGroup.LayoutParams.MatchParent : lp.Height; //ViewGroup.LayoutParams.WrapContent; window.Attributes = lp; } //var backgroundImage = dialogController?.BackgroundImage; // //if (backgroundImage != null) //{ // //Window window = alertDialog.Window; // //window.SetBackgroundDrawable(backgroundImage);; //} alertDialog.CancelEvent += delegate { resultSource.TrySetResult(-1); }; if (dialogController != null) { dialogController.CloseRequested += delegate { if (alertDialog.IsShowing) { alertDialog.Cancel(); } }; } /* Subscribing to the DismissEvent to set the result source * is unnecessary as other events are always raised. * The DismissEvent is, however, always raised and thus * we place the bodyView removal code here. */ alertDialog.DismissEvent += (sender, args) => { Interlocked.Decrement(ref openDialogCount); builder.SetView(null); try { (bodyView?.Parent as ViewGroup)?.RemoveView(bodyView); } catch (ObjectDisposedException) { /* View was already disposed in user code. */ } catch (Exception ex) { var log = Dependency.Resolve <ILog>(); log.Debug("Exception raised when removing view from alert.", ex); } }; if (AlertDialogDividerColor.HasValue) { var resources = context.Resources; int id = resources.GetIdentifier("titleDivider", "id", "android"); View titleDivider = alertDialog.FindViewById(id); if (titleDivider != null) { var color = AlertDialogDividerColor.Value; if (color == Color.Transparent) { titleDivider.Visibility = ViewStates.Gone; } titleDivider.SetBackgroundColor(color); } } if (AlertDialogTitleColor.HasValue) { var resources = context.Resources; int id = resources.GetIdentifier("alertTitle", "id", "android"); var textView = alertDialog.FindViewById <TextView>(id); if (textView != null) { var color = AlertDialogTitleColor.Value; textView.SetTextColor(color); } } if (AlertDialogBackgroundColor.HasValue) { var v = bodyView ?? alertDialog.ListView; v.SetBackgroundColor(AlertDialogBackgroundColor.Value); } } catch (WindowManagerBadTokenException ex) { /* See http://stackoverflow.com/questions/2634991/android-1-6-android-view-windowmanagerbadtokenexception-unable-to-add-window*/ resultSource.SetException(new Exception( "Unable to use the Application.Context object to create a dialog. Please either set the Context property of this DialogService or register the current activity using Dependency.Register<Activity>(myActivity)", ex)); } }, null); return(resultSource.Task); }