public void SetPositiveButton(string text, EventHandler <DialogClickEventArgs> handler) { if (_useAppCompat) { _appcompatBuilder?.SetPositiveButton(text, handler); } else { _legacyBuilder?.SetPositiveButton(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; }); }
//Register new LocalBox part 4 public void SetUpPassphrase(LocalBox localBox) { LayoutInflater factory = LayoutInflateHelper.GetLayoutInflater(homeActivity); View viewNewPhrase = factory.Inflate(Resource.Layout.dialog_new_passphrase, null); EditText editNewPassphrase = (EditText)viewNewPhrase.FindViewById <EditText> (Resource.Id.editText_dialog_new_passphrase); EditText editNewPassphraseVerify = (EditText)viewNewPhrase.FindViewById <EditText> (Resource.Id.editText_dialog_new_passphrase_verify); var dialogBuilder = new AlertDialog.Builder(homeActivity); dialogBuilder.SetTitle("Passphrase"); dialogBuilder.SetView(viewNewPhrase); dialogBuilder.SetPositiveButton("OK", (EventHandler <DialogClickEventArgs>)null); dialogBuilder.SetNegativeButton(Resource.String.cancel, (EventHandler <DialogClickEventArgs>)null); var dialog = dialogBuilder.Create(); dialog.Show(); var buttonCancel = dialog.GetButton((int)DialogButtonType.Negative); var buttonAddPassphrase = dialog.GetButton((int)DialogButtonType.Positive); buttonAddPassphrase.Click += async(sender, args) => { string passphraseOne = editNewPassphrase.Text; string passphraseTwo = editNewPassphraseVerify.Text; if (String.IsNullOrEmpty(passphraseOne)) { homeActivity.ShowToast("Passphrase is niet ingevuld"); } else if (String.IsNullOrEmpty(passphraseTwo)) { homeActivity.ShowToast("U dient uw ingevoerde passphrase te verifieren"); } else { if (!passphraseOne.Equals(passphraseTwo)) { homeActivity.ShowToast("De ingevoerde passphrases komen niet overeen. Corrigeer dit a.u.b."); } else { try { homeActivity.ShowProgressDialog("Passphrase aanmaken. Dit kan enige tijd in beslag nemen. Een ogenblik geduld a.u.b."); bool newPassphraseSucceeded = await BusinessLayer.Instance.SetPublicAndPrivateKey(localBox, passphraseOne); homeActivity.HideProgressDialog(); if (!newPassphraseSucceeded) { homeActivity.ShowToast("Passphrase instellen mislukt. Probeer het a.u.b. opnieuw"); } else { dialog.Dismiss(); homeActivity.ShowToast("LocalBox succesvol geregistreerd"); homeActivity.menuFragment.UpdateLocalBoxes(); SplashActivity.intentData = null; } } catch (Exception ex) { Insights.Report(ex); homeActivity.HideProgressDialog(); homeActivity.ShowToast("Passphrase instellen mislukt. Probeer het a.u.b. opnieuw"); } } } }; buttonCancel.Click += (sender, args) => { DataLayer.Instance.DeleteLocalBox(localBox.Id); homeActivity.menuFragment.UpdateLocalBoxes(); dialog.Dismiss(); }; }
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); } }
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); }
private async Task SendFiles(string[] files) { if (TrialHelper.UserTrialStatus == QuickShare.Common.Service.UpgradeDetails.VersionStatus.TrialVersion) { double totalSize = 0; foreach (var item in files) { var info = new System.IO.FileInfo(item); totalSize += info.Length; } totalSize /= 1024.0 * 1024.0; if (totalSize > Constants.MaxSizeForTrialVersion) { var intent = new Intent(this, typeof(MessageShowActivity)); intent.PutExtra("message", "trialNotice"); StartActivity(intent); Finish(); return; } } sendStatus.Text = "Connecting..."; var result = await Common.PackageManager.Connect(Common.GetCurrentRemoteSystem(), false); if (result != QuickShare.Common.Rome.RomeAppServiceConnectionStatus.Success) { Analytics.TrackEvent("SendToWindows", "file", "Failed"); sendStatus.Text = $"Connect failed. ({result.ToString()})"; return; } //Fix Rome Android bug (receiver app service closes after 5 seconds in first connection) Common.PackageManager.CloseAppService(); result = await Common.PackageManager.Connect(Common.GetCurrentRemoteSystem(), false); if (result != QuickShare.Common.Rome.RomeAppServiceConnectionStatus.Success) { Analytics.TrackEvent("SendToWindows", "file", "Failed"); sendStatus.Text = $"Connect failed. ({result.ToString()})"; return; } string sendingText = (files.Length == 1) ? "Sending file..." : "Sending files..."; sendStatus.Text = "Preparing..."; string message = ""; FileTransferResult transferResult = FileTransferResult.Successful; using (FileSender fs = new FileSender(Common.GetCurrentRemoteSystem(), new WebServerComponent.WebServerGenerator(), Common.PackageManager, FindMyIPAddresses(), CrossDeviceInfo.Current.Model)) { sendProgress.Max = 1; fs.FileTransferProgress += (ss, ee) => { if (ee.State == FileTransferState.Error) { transferResult = FileTransferResult.FailedOnSend; message = ee.Message; } else { RunOnUiThread(() => { sendStatus.Text = sendingText; SetProgressBarValue((int)ee.CurrentPart, (int)ee.Total + 1); }); } }; if (files.Length == 0) { sendStatus.Text = "No files."; //ViewModel.ProgressIsIndeterminate = false; return; } else if (files.Length == 1) { await Task.Run(async() => { sendingFile = true; transferResult = await fs.SendFile(sendFileCancellationTokenSource.Token, new PCLStorage.FileSystemFile(files[0])); sendingFile = false; }); } else { await Task.Run(async() => { sendingFile = true; transferResult = await fs.SendFiles(sendFileCancellationTokenSource.Token, from x in files select new PCLStorage.FileSystemFile(x), DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + "\\"); sendingFile = false; }); } sendProgress.Progress = sendProgress.Max; } Dictionary <string, object> vs = new Dictionary <string, object> { { "Receiver", "System" }, { "FinishService", "FinishService" }, }; await Common.PackageManager.Send(vs); Common.PackageManager.CloseAppService(); SetProgressBarValueToMax(); if (transferResult != FileTransferResult.Successful) { Analytics.TrackEvent("SendToWindows", "file", transferResult.ToString()); if (transferResult != FileTransferResult.Cancelled) { sendStatus.Text = "Failed."; System.Diagnostics.Debug.WriteLine("Send failed.\r\n\r\n" + message); if (transferResult == FileTransferResult.FailedOnHandshake) { message = "Couldn't reach remote device.\r\n\r\n" + "Make sure both devices are connected to the same Wi-Fi or LAN network."; } AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle(message); alert.SetPositiveButton("OK", (senderAlert, args) => { }); RunOnUiThread(() => { alert.Show(); }); } } else { sendStatus.Text = "Finished."; Analytics.TrackEvent("SendToWindows", "file", "Success"); } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); this.SetContentView(Resource.Layout.NewGame); // Create your application here EditText pName = FindViewById <EditText>(Resource.Id.txtGameName); // games list ListView pGamesList = FindViewById <ListView>(Resource.Id.gamesList); pGamesList.Adapter = new DrawerItemCustomAdapter(this, Resource.Layout.ListViewItemRow, m_lGameTypes.ToArray()); pGamesList.ItemClick += (object sender, Android.Widget.AdapterView.ItemClickEventArgs e) => { int iChoice = e.Position; m_sSelectedType = m_lGameTypes[iChoice]; TextView pGameType = FindViewById <TextView>(Resource.Id.txtGameType); pGameType.Text = "Game type - " + m_sSelectedType; }; Button pSubmit = FindViewById <Button>(Resource.Id.btnSubmitGame); pSubmit.Click += delegate { if (m_sSelectedType == "") { var pBuilder = new AlertDialog.Builder(this); pBuilder.SetMessage("You must select a game type"); pBuilder.SetPositiveButton("Ok", (e, s) => { return; }); pBuilder.Show(); } else if (pName.Text == "") { var pBuilder = new AlertDialog.Builder(this); pBuilder.SetMessage("Please enter a name for your game"); pBuilder.SetPositiveButton("Ok", (e, s) => { return; }); pBuilder.Show(); } else { string sBody = Master.BuildCommonBody("<param name='sGameName'>" + pName.Text.ToString() + "</param>"); string sResponse = WebCommunications.SendPostRequest(Master.GetBaseURL() + Master.GetGameURL(m_sSelectedType) + "CreateNewGame", sBody, true); XElement pResponse = Master.ReadResponse(sResponse); string sResponseMessage = pResponse.Element("Text").Value; var pBuilder = new AlertDialog.Builder(this); pBuilder.SetMessage(sResponseMessage); if (pResponse.Attribute("Type").Value == "Error") { pBuilder.SetPositiveButton("Ok", (e, s) => { return; }); } else { pBuilder.SetPositiveButton("Ok", (e, s) => { this.SetResult(Result.Ok); this.Finish(); }); } pBuilder.Create().Show(); } }; }
void IPickerRenderer.OnClick() { 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 = 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?.Dispose(); _dialog = null; }; _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); }
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 bundle) { base.OnCreate(bundle);; string TxtToVoice = this.Intent.GetStringExtra("TxtToVoice"); int para2 = this.Intent.GetIntExtra("DelayTime", -1); isRecording = false; SetContentView(Resource.Layout.TextToLuisMain); textBox = FindViewById <TextView>(Resource.Id.textYourText); LuisBox_Intent = FindViewById <TextView>(Resource.Id.LuisIntentText); LuisBox_Entiti = FindViewById <TextView>(Resource.Id.LuisEntitiText); int para3 = this.Intent.GetIntExtra("para3", -1); if (para3 >= 0) { VoiceIndex = para3; para3 = 0; PollingJobTime(300, para3); } else { PollingJobTime(300, 0); } textToSpeech = new TextToSpeech(this, this, "com.google.android.tts"); var langAvailable = new List <string> { "Default" }; // our spinner only wants to contain the languages supported by the tts and ignore the rest var localesAvailable = Java.Util.Locale.GetAvailableLocales().ToList(); foreach (var locale in localesAvailable) { LanguageAvailableResult res = textToSpeech.IsLanguageAvailable(locale); switch (res) { case LanguageAvailableResult.Available: langAvailable.Add(locale.DisplayLanguage); break; case LanguageAvailableResult.CountryAvailable: langAvailable.Add(locale.DisplayLanguage); break; case LanguageAvailableResult.CountryVarAvailable: langAvailable.Add(locale.DisplayLanguage); break; } } langAvailable = langAvailable.OrderBy(t => t).Distinct().ToList(); var adapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, langAvailable); // set up the speech to use the default langauge // if a language is not available, then the default language is used. lang = Java.Util.Locale.Default; textToSpeech.SetLanguage(lang); // set the speed and pitch textToSpeech.SetPitch(.9f); textToSpeech.SetSpeechRate(.9f); // check to see if we can actually record - if we can, assign the event to the button string rec = Android.Content.PM.PackageManager.FeatureMicrophone; if (rec != "android.hardware.microphone") { // no microphone, no recording. Disable the button and output an alert var alert = new AlertDialog.Builder(recButton.Context); alert.SetTitle("You don't seem to have a microphone to record with"); alert.SetPositiveButton("OK", (sender, e) => { textBox.Text = "No microphone present"; recButton.Enabled = false; return; }); 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); }
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); }
private void ProfilePopup() { var menu = new PopupMenu(this, search); menu.Inflate(Resource.Menu.Popup); int count = 0; foreach (Profiel p in _appController.DistinctProfielen) { menu.Menu.Add(0, count, count, p.name); count++; } menu.Menu.Add(0, count, count, "Nieuw profiel"); menu.MenuItemClick += (s1, arg1) => { if (arg1.Item.ItemId == count) { var alert = new AlertDialog.Builder(this); alert.SetTitle("Nieuw profiel"); var input = new EditText(this); input.InputType = InputTypes.TextFlagCapWords; input.Hint = "Naam"; KeyboardHelper.ShowKeyboard(this, input); alert.SetView(input); alert.SetPositiveButton("Ok", (s, args) => { string value = input.Text; if (value.Replace("'", "").Replace(" ", "").Equals("")) { mToastShort.SetText("Ongeldige naam"); mToastShort.Show(); } else if (_appController.GetProfielNamen().Contains(value)) { input.Text = ""; mToastShort.SetText("Profiel " + value + " bestaat al"); mToastShort.Show(); } else { _appController.AddProfile(value); _appController.AddOrUpdateEigenschappenSer(value, JsonSerializer.SerializeToString(_appController.Eigenschappen)); mToastShort.SetText("Selectie opgeslagen voor profiel " + value); mToastShort.Show(); } }); AlertDialog d1 = alert.Create(); //add profile when enter is clicked input.EditorAction += (s2, e) => { if (e.ActionId == ImeAction.Done) { d1.GetButton(-1).PerformClick(); } else { e.Handled = false; } }; RunOnUiThread(d1.Show); } else { _appController.AddOrUpdateEigenschappenSer(arg1.Item.TitleFormatted.ToString(), JsonSerializer.SerializeToString(_appController.Eigenschappen)); mToastShort.SetText("Selectie opgeslagen voor profiel " + arg1.Item.TitleFormatted); mToastShort.Show(); } }; menu.Show(); }
private async void butonTiklandiAsync(object sender, EventArgs e) { var button = sender as Button; var status = await CrossPermissions.Current.CheckPermissionStatusAsync <StoragePermission>(); if (status != PermissionStatus.Granted) { if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Storage)) { Toast.MakeText(Application.Context, Resources.GetText(Resource.String.fileperrmisson), ToastLength.Long).Show(); } status = await CrossPermissions.Current.RequestPermissionAsync <StoragePermission>(); } yuklemeBar.Visibility = ViewStates.Visible; if (txtEmail.Text.Length <= 0 || txtPassword.Text.Length <= 0) { HataGoster(Resources.GetText(Resource.String.passwordempty)); yuklemeBar.Visibility = ViewStates.Invisible; return; } userSession = new UserSessionData { UserName = txtEmail.Text, Password = txtPassword.Text }; _instaApi = InstaApiBuilder.CreateBuilder() .SetUser(userSession) .SetRequestDelay(RequestDelay.FromSeconds(0, 0)) .Build(); _instaApi.SetTimeout(TimeSpan.FromMinutes(10)); if (!_instaApi.IsUserAuthenticated) { var logInResult = await _instaApi.LoginAsync(); if (!logInResult.Succeeded) { switch (logInResult.Value) { case InstaLoginResult.TwoFactorRequired: { var et = new EditText(this); var ad = new AlertDialog.Builder(this); et.InputType = InputTypes.ClassNumber; ad.SetTitle("Two Factor Code Required"); ad.SetView(et); ad.SetCancelable(false); ad.SetPositiveButton("OK", async delegate { ad.Dispose(); yuklemeBar.Visibility = ViewStates.Visible; if (et.Text == null && et.Text.Length < 5) { HataGoster("2 Factor code cannot be shorter than 6"); } var twoFactorLogin = await _instaApi.TwoFactorLoginAsync(et.Text); if (twoFactorLogin.Succeeded) { await girisYapti(button, _instaApi); var state2 = await _instaApi.GetStateDataAsStreamAsync(); await using var fileStream2 = File.Create(stateFile); state2.Seek(0, SeekOrigin.Begin); await state2.CopyToAsync(fileStream2); } else { Toast.MakeText(Application.Context, twoFactorLogin.Info.Message, ToastLength.Long) ?.Show(); HataGoster(twoFactorLogin.Info.Message); } } ); ad.Show(); break; }
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; } }
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(); }
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)); 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(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); }
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); }
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(); }
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); }
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 static void ShowChangeLog(Context ctx, Action onDismiss) { AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(ctx, Android.Resource.Style.ThemeHoloLightDialog)); builder.SetTitle(ctx.GetString(Resource.String.ChangeLog_title)); List <string> changeLog = new List <string> { ctx.GetString(Resource.String.ChangeLog_1_07b), ctx.GetString(Resource.String.ChangeLog_1_07), ctx.GetString(Resource.String.ChangeLog_1_06), ctx.GetString(Resource.String.ChangeLog_1_05), ctx.GetString(Resource.String.ChangeLog_1_04b), ctx.GetString(Resource.String.ChangeLog_1_04), ctx.GetString(Resource.String.ChangeLog_1_03), ctx.GetString(Resource.String.ChangeLog_1_02), #if !NoNet ctx.GetString(Resource.String.ChangeLog_1_01g), ctx.GetString(Resource.String.ChangeLog_1_01d), #endif ctx.GetString(Resource.String.ChangeLog_1_01), ctx.GetString(Resource.String.ChangeLog_1_0_0e), ctx.GetString(Resource.String.ChangeLog_1_0_0), ctx.GetString(Resource.String.ChangeLog_0_9_9c), ctx.GetString(Resource.String.ChangeLog_0_9_9), ctx.GetString(Resource.String.ChangeLog_0_9_8c), ctx.GetString(Resource.String.ChangeLog_0_9_8b), ctx.GetString(Resource.String.ChangeLog_0_9_8), #if !NoNet //0.9.7b fixes were already included in 0.9.7 offline ctx.GetString(Resource.String.ChangeLog_0_9_7b), #endif ctx.GetString(Resource.String.ChangeLog_0_9_7), ctx.GetString(Resource.String.ChangeLog_0_9_6), ctx.GetString(Resource.String.ChangeLog_0_9_5), ctx.GetString(Resource.String.ChangeLog_0_9_4), ctx.GetString(Resource.String.ChangeLog_0_9_3_r5), ctx.GetString(Resource.String.ChangeLog_0_9_3), ctx.GetString(Resource.String.ChangeLog_0_9_2), ctx.GetString(Resource.String.ChangeLog_0_9_1), ctx.GetString(Resource.String.ChangeLog_0_9), ctx.GetString(Resource.String.ChangeLog_0_8_6), ctx.GetString(Resource.String.ChangeLog_0_8_5), ctx.GetString(Resource.String.ChangeLog_0_8_4), ctx.GetString(Resource.String.ChangeLog_0_8_3), ctx.GetString(Resource.String.ChangeLog_0_8_2), ctx.GetString(Resource.String.ChangeLog_0_8_1), ctx.GetString(Resource.String.ChangeLog_0_8), ctx.GetString(Resource.String.ChangeLog_0_7), ctx.GetString(Resource.String.ChangeLog) }; String version; try { PackageInfo packageInfo = ctx.PackageManager.GetPackageInfo(ctx.PackageName, 0); version = packageInfo.VersionName; } catch (PackageManager.NameNotFoundException) { version = ""; } string warning = ""; if (version.Contains("pre")) { warning = ctx.GetString(Resource.String.PreviewWarning); } builder.SetPositiveButton(Android.Resource.String.Ok, (dlgSender, dlgEvt) => { ((AlertDialog)dlgSender).Dismiss(); }); builder.SetCancelable(false); WebView wv = new WebView(ctx); wv.SetBackgroundColor(Color.White); wv.LoadDataWithBaseURL(null, GetLog(changeLog, warning, ctx), "text/html", "UTF-8", null); //builder.SetMessage(""); builder.SetView(wv); Dialog dialog = builder.Create(); dialog.DismissEvent += (sender, e) => { onDismiss(); }; dialog.Show(); /*TextView message = (TextView)dialog.FindViewById(Android.Resource.Id.Message); * * * message.TextFormatted = Html.FromHtml(ConcatChangeLog(ctx, changeLog.ToArray())); * message.AutoLinkMask=MatchOptions.WebUrls;*/ }
private void ButtonBackup_Click(object sender, EventArgs eventArgs) { bool isGranted = new SdCardAccess().Grand(this); if (!isGranted) { return; } // Vor dem Backup ggf. die User-Kategorien ggf. speichern, // damit es auch im Backup ist. this.SaveUserDefinedCategories(); var databaseFilePath = Android_Database.Instance.GetProductiveDatabasePath(); var downloadFolder = Android.OS.Environment.GetExternalStoragePublicDirectory( Android.OS.Environment.DirectoryDownloads).AbsolutePath; string backupFileName; string databaseFileName = Path.GetFileNameWithoutExtension(databaseFilePath); if (databaseFileName == "Vorraete") { backupFileName = string.Format("Vue_{0}.VueBak", DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss")); } else { backupFileName = string.Format(databaseFileName + "_{0}.VueBak", DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss")); } var backupFilePath = Path.Combine(downloadFolder, backupFileName); Android_Database.Instance.CloseConnection(); var progressDialog = this.CreateProgressBar(Resource.Id.ProgressBar_BackupAndRestore); new Thread(new ThreadStart(delegate { string message; try { File.Copy(databaseFilePath, backupFilePath); message = string.Format( "Datenbank im Download Verzeichnis gesichert als:\n\n {0}" + "\n\nSichern Sie diese Datei auf Google Drive oder auf Ihren PC.", backupFilePath); } catch (Exception ex) { message = ex.Message; } this.HideProgressBar(progressDialog); RunOnUiThread(() => { var builder = new AlertDialog.Builder(this); builder.SetMessage(message); builder.SetPositiveButton("Ok", (s, e) => { }); builder.Create().Show(); }); })).Start(); return; }
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 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(); }
private void SamplePageContents(Android.Content.Context con) { //Title list Title.Add("Software"); Title.Add("Banking"); Title.Add("Media"); Title.Add("Medical"); //jobSearchLabel jobSearchLabel = new TextView(con); jobSearchLabel.Text = "Job Search"; jobSearchLabel.TextSize = 30; jobSearchLabel.Typeface = Typeface.DefaultBold; //jobSearchLabelSpacing jobSearchLabelSpacing = new TextView(con); jobSearchLabelSpacing.SetHeight(40); //countryLabel countryLabel = new TextView(con); countryLabel.Text = "Country"; countryLabel.TextSize = 16; //countryLabelSpacing countryLabelSpacing = new TextView(con); countryLabelSpacing.SetHeight(10); //countryAutoCompleteSpacing countryAutoCompleteSpacing = new TextView(con); countryAutoCompleteSpacing.SetHeight(30); //jobFieldLabel jobFieldLabel = new TextView(con); jobFieldLabel.Text = "Job Field"; jobFieldLabel.TextSize = 16; //jobFieldLabelSpacing jobFieldLabelSpacing = new TextView(con); jobFieldLabelSpacing.SetHeight(10); //jobFieldAutoCompleteSpacing jobFieldAutoCompleteSpacing = new TextView(con); jobFieldAutoCompleteSpacing.SetHeight(30); //experienceLabel experienceLabel = new TextView(con); experienceLabel.Text = "Experience"; experienceLabel.TextSize = 16; //experienceLabelSpacing experienceLabelSpacing = new TextView(con); experienceLabelSpacing.SetHeight(10); //Experience list Experience.Add("1"); Experience.Add("2"); //searchButton searchButton = new Button(con); searchButton.SetWidth(ActionBar.LayoutParams.MatchParent); searchButton.SetHeight(40); searchButton.Text = "Search"; searchButton.SetTextColor(Color.White); searchButton.SetBackgroundColor(Color.Gray); searchButton.Click += (object sender, EventArgs e) => { GetResult(); resultsDialog.SetMessage(jobNumber + " Jobs Found"); resultsDialog.Create().Show(); }; //searchButtonSpacing searchButtonSpacing = new TextView(con); searchButtonSpacing.SetHeight(30); //experience Spinner experienceSpinner = new Spinner(con, SpinnerMode.Dialog); experienceSpinner.DropDownWidth = 500; experienceSpinner.SetBackgroundColor(Color.Gray); ArrayAdapter <String> experienceDataAdapter = new ArrayAdapter <String> (con, Android.Resource.Layout.SimpleSpinnerItem, Experience); experienceDataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); experienceSpinner.Adapter = experienceDataAdapter; //experienceSpinnerSpacing experienceSpinnerSpacing = new TextView(con); experienceSpinnerSpacing.SetHeight(30); //results dialog resultsDialog = new AlertDialog.Builder(con); resultsDialog.SetTitle("Results"); resultsDialog.SetPositiveButton("OK", (object sender, DialogClickEventArgs e) => { }); resultsDialog.SetCancelable(true); }
private void spawnFilterDialog() { selectedItems.Add(0); selectedItems.Add(1); selectedItems.Add(2); var builder = new AlertDialog.Builder(ViewContext) .SetTitle("Filter Events") .SetMultiChoiceItems(items, new bool[] {true,true,true}, MultiListClicked); builder.SetPositiveButton("Ok", OkClicked); builder.Create(); 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); }
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 }; }
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.Inflate(Resource.Layout.Unsigned_conversion_layout, container, false); EditText inText = view.FindViewById <EditText>(Resource.Id.input); TextView outText = view.FindViewById <TextView>(Resource.Id.outputText); Spinner inSpinner = view.FindViewById <Spinner>(Resource.Id.inSpinner); Spinner outSpinner = view.FindViewById <Spinner>(Resource.Id.outSpinner); var inAdapter = ArrayAdapter.CreateFromResource(container.Context, Resource.Array.data_units, Resource.Layout.my_spinner); inSpinner.Adapter = inAdapter; inAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); var outAdapter = ArrayAdapter.CreateFromResource(container.Context, Resource.Array.data_units, Resource.Layout.my_spinner); outSpinner.Adapter = outAdapter; outAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); outText.Click += delegate { AlertDialog.Builder builder = new AlertDialog.Builder(this.Context); builder.SetTitle("Output"); builder.SetMessage(Convert.ToString(outText.Text)); builder.SetPositiveButton("Done", delegate { }); builder.Show(); }; outSpinner.ItemSelected += delegate { double input; bool validInput = Double.TryParse(inText.Text, out input); if (validInput) { outText.Text = Convert_units(input, inSpinner.SelectedItemId, outSpinner.SelectedItemId); } else { outText.Text = ""; } }; var convert = view.FindViewById(Resource.Id.convert_btn); convert.Click += delegate { double input; bool validInput = Double.TryParse(inText.Text, out input); if (validInput) { outText.Text = Convert_units(input, inSpinner.SelectedItemId, outSpinner.SelectedItemId); } else { Toast.MakeText(this.Context, "Enter decimal value", ToastLength.Long).Show(); } }; return(view); }
public void ShowNewFolderDialog() { LayoutInflater factory = LayoutInflateHelper.GetLayoutInflater(homeActivity); View viewNewFolder = factory.Inflate(Resource.Layout.dialog_new_folder, null); EditText editTextFolderName = (EditText)viewNewFolder.FindViewById <EditText> (Resource.Id.editText_dialog_folder_name); //Build the dialog var dialogBuilder = new AlertDialog.Builder(homeActivity); dialogBuilder.SetTitle(Resource.String.folder_new); dialogBuilder.SetView(viewNewFolder); dialogBuilder.SetPositiveButton(Resource.String.add, (EventHandler <DialogClickEventArgs>)null); dialogBuilder.SetNegativeButton(Resource.String.cancel, (EventHandler <DialogClickEventArgs>)null); var dialog = dialogBuilder.Create(); dialog.Show(); //Get the buttons var buttonAddFolder = dialog.GetButton((int)DialogButtonType.Positive); var buttonCancel = dialog.GetButton((int)DialogButtonType.Negative); buttonAddFolder.Click += async(sender, args) => { if (String.IsNullOrEmpty(editTextFolderName.Text)) { homeActivity.ShowToast("Naam is niet ingevuld"); } else { homeActivity.ShowProgressDialog("Map wordt aangemaakt. Een ogenblik geduld a.u.b."); try{ int numberOfDirectoriesOpened = ExplorerFragment.openedDirectories.Count; string directoryNameToUploadFileTo = ExplorerFragment.openedDirectories [numberOfDirectoriesOpened - 1]; bool addedSuccesfully = (await DataLayer.Instance.CreateFolder(System.IO.Path.Combine(directoryNameToUploadFileTo, (editTextFolderName.Text)))); dialog.Dismiss(); if (!addedSuccesfully) { homeActivity.HideProgressDialog(); homeActivity.ShowToast("Toevoegen map mislukt. Probeer het a.u.b. opnieuw"); } else { homeActivity.HideProgressDialog(); homeActivity.ShowToast("Map succesvol toegevoegd"); //Refresh data homeActivity.RefreshExplorerFragmentData(); } }catch (Exception ex) { Insights.Report(ex); homeActivity.HideProgressDialog(); homeActivity.ShowToast("Toevoegen map mislukt. Probeer het a.u.b. opnieuw"); } } }; buttonCancel.Click += (sender, args) => { dialog.Dismiss(); }; }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "Tabbed" layout resource SetContentView(Resource.Layout.Tabbed); // Get settings ISharedPreferences settings = GetSharedPreferences("be.chiro.bivak.settings", 0); //Toen waarschuwingen als je niet terugkomt van een call if (Globals.CALLED == false) { // de settings zijn nog nooit opgeslagen if (settings.GetBoolean("ingevuld", false) == false) { AlertDialog.Builder sendMessage = new AlertDialog.Builder(this); sendMessage.SetTitle("Vul je gegevens in"); sendMessage.SetMessage("Om je optimaal te kunnen helpen als er iets mis gaat hebben we je gegevens nodig. Bekijk even de instellingen om ze in te vullen"); sendMessage.SetPositiveButton("OK", delegate {}); sendMessage.Show(); } //De settings zijn nog niet volledig else if (settings.GetString("naam", "") == "" || settings.GetString("groep", "") == "") { Android.Widget.Toast.MakeText(this, "Je hebt je naam en/of je chirogroep nog niet ingevuld", ToastLength.Long).Show(); } //reset global var CALLED Globals.CALLED = false; } // For Warnings we use chirorood Color chirorood = new Color(225, 20, 60, 225); //R, G, B, alpha // Find ID of infotext TextView infoText = FindViewById <TextView> (Resource.Id.infoText); //Show a different text between 09h and 17h var hour = DateTime.Now.Hour; var day = DateTime.Now.DayOfWeek; if (9 <= hour && hour < 17) { infoText.SetText(Resource.String.voor18u); } else { infoText.SetText(Resource.String.na18u); infoText.SetBackgroundColor(chirorood); } // Als het zaterdag of zondag is doen we sowieso alsof het na 18u is. if (day == DayOfWeek.Saturday || day == DayOfWeek.Sunday) { infoText.SetText(Resource.String.na18u); infoText.SetBackgroundColor(chirorood); } // Get our button from the layout resource, // and attach an event to it Button button = FindViewById <Button> (Resource.Id.myButton); button.Click += delegate { //sendMessage.Show(); belKipdorp(); }; }
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( ); } ); }