I'm developping an application with Xamarin for iOS. I have a page that is filled with a UIStackView that I populate with an image and buttons.
Everything works fine, despite the fact that nothing is visible, but if I click where the buttons should appear, it executes the good behaviour of the button (opening another page).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Foundation;
using UIKit;
using CoreGraphics;
using Cirrious.FluentLayouts.Touch;
namespace SmartTransportNatif.iOS
{
public class MainViewController : UIViewController
{
UIButton btn;
JourneyViewController journey;
Dictionary<string, string> favStations;
UIStackView stkView;
public override void ViewDidLoad()
{
base.ViewDidLoad();
View.BackgroundColor = UIColor.White;
Title = "Accueil";
journey = new JourneyViewController();
MyClass pcl = new MyClass();
favStations = pcl.getFavStations();
var img = new UIImageView(View.Frame);
img.Image = UIImage.FromFile("train.png");
var bounds = UIScreen.MainScreen.Bounds;
stkView = new UIStackView(bounds);
stkView.Axis = UILayoutConstraintAxis.Vertical;
stkView.Distribution = UIStackViewDistribution.FillEqually;
stkView.Spacing = 5;
stkView.AddArrangedSubview(img);
View.AddSubview(stkView);
foreach(KeyValuePair<string, string> entry in favStations)
{
addButton(entry.Key, entry.Value);
}
}
void addButton(string name, string station)
{
var btn = UIButton.FromType(UIButtonType.System);
btn.Frame = new CGRect(0, 0, 280, 44);
btn.SetTitle(name, UIControlState.Normal);
btn.BackgroundColor = new UIColor(33,150,234,255);
btn.SetTitleColor(new UIColor(255,255,255,255),
UIControlState.Normal);
btn.TouchUpInside += (sender, e) =>
{
this.NavigationController.PushViewController(journey, true);
};
stkView.AddArrangedSubview(btn);
}
}
}
Does someone see what is wrong or missing?
Related
I wanted to make a text to speech application for a project and I used this as a reference: https://github.com/xamarin/monodroid-samples/tree/main/PlatformFeatures/TextToSpeech
However, whenever i open the app it always opens up the google tts service and I cannot change the language, and the spinner does not show any languages only "Default" is there a way to make this program not open up google tts service each time and making the language options available on the spinner? thanks so much!
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.Support.V7.App;
using Android.Speech.Tts;
using Java.Util;
using Android.Graphics;
namespace DND_Connect
{
[Activity(Label = "Deaf")]
public class DeafPage : Activity, TextToSpeech.IOnInitListener
{
TextToSpeech textToSpeech;
Context context;
private readonly int MyCheckCode = 101, NeedLang = 103;
Java.Util.Locale lang;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.deaf);
var btnSayIt = FindViewById<Button>(Resource.Id.buttonSpeak);
var editWhatToSay = FindViewById<EditText>(Resource.Id.edtSpch);
var spinLanguages = FindViewById<Spinner>(Resource.Id.spnLng);
var txtSpeedVal = FindViewById<TextView>(Resource.Id.txtSpeed);
var txtPitchVal = FindViewById<TextView>(Resource.Id.txtPitch);
var seekSpeed = FindViewById<SeekBar>(Resource.Id.skSpeed);
var seekPitch = FindViewById<SeekBar>(Resource.Id.skPitch);
var txtView = FindViewById<TextView>(Resource.Id.deaftitle);
var txtView1 = FindViewById<TextView>(Resource.Id.deafdesc);
Typeface tf = Typeface.CreateFromAsset(Assets, "Roboto-Condensed.ttf");
txtView.SetTypeface(tf, Android.Graphics.TypefaceStyle.Normal);
txtView1.SetTypeface(tf, Android.Graphics.TypefaceStyle.Normal);
seekSpeed.Progress = seekPitch.Progress = 127;
txtSpeedVal.Text = txtPitchVal.Text = "0.5";
context = btnSayIt.Context;
textToSpeech = new TextToSpeech(this, this, "com.google.android.tts");
var langAvailable = new List<string> { "Default" };
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);
spinLanguages.Adapter = adapter;
lang = Java.Util.Locale.Default;
textToSpeech.SetLanguage(lang);
textToSpeech.SetPitch(.5f);
textToSpeech.SetSpeechRate(.5f);
btnSayIt.Click += delegate
{
if (!string.IsNullOrEmpty(editWhatToSay.Text))
textToSpeech.Speak(editWhatToSay.Text, QueueMode.Flush, null);
};
seekPitch.StopTrackingTouch += (object sender, SeekBar.StopTrackingTouchEventArgs e) =>
{
var seek = sender as SeekBar;
var progress = seek.Progress / 255f;
textToSpeech.SetPitch(progress);
txtPitchVal.Text = progress.ToString("F2");
};
seekSpeed.StopTrackingTouch += (object sender, SeekBar.StopTrackingTouchEventArgs e) =>
{
var seek = sender as SeekBar;
var progress = seek.Progress / 255f;
textToSpeech.SetSpeechRate(progress);
txtSpeedVal.Text = progress.ToString("F2");
};
spinLanguages.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) =>
{
lang = Java.Util.Locale.GetAvailableLocales().FirstOrDefault(t => t.DisplayLanguage == langAvailable[(int)e.Id]);
var checkTTSIntent = new Intent();
checkTTSIntent.SetAction(TextToSpeech.Engine.ActionCheckTtsData);
StartActivityForResult(checkTTSIntent, NeedLang);
};
}
void TextToSpeech.IOnInitListener.OnInit(OperationResult status)
{
if (status == OperationResult.Error)
textToSpeech.SetLanguage(Java.Util.Locale.Default);
if (status == OperationResult.Success)
textToSpeech.SetLanguage(lang);
}
protected override void OnActivityResult(int req, Result res, Intent data)
{
if (req == NeedLang)
{
var installTTS = new Intent();
installTTS.SetAction(TextToSpeech.Engine.ActionInstallTtsData);
StartActivity(installTTS);
}
}
}
}
[assembly: Xamarin.Forms.Dependency(typeof(TextToSpeechImplementation))]
namespace ShopFloor_Automation.Droid.Implementations
{
public class TextToSpeechImplementation : Java.Lang.Object, ITextToSpeech, TextToSpeech.IOnInitListener
{
TextToSpeech speaker;
string toSpeak;
public TextToSpeechImplementation() { }
public void OnInit([GeneratedEnum] OperationResult status)
{
if (status.Equals(OperationResult.Success))
{
var p = new Dictionary<string, string>();
speaker.Speak(toSpeak, QueueMode.Flush, p);
}
}
public void Speak(string text)
{
var ctx = Forms.Context; // useful for many Android SDK features
toSpeak = text;
if (speaker == null)
{
speaker = new TextToSpeech(ctx, this);
}
else
{
var p = new Dictionary<string, string>();
speaker.Speak(toSpeak, QueueMode.Flush, p);
}
}
}
}
I am creating a login form using Xamarin which accepts email, password fields.
After the user enters his details and clicks on login button, no alert box is displayed. It comes out of the app. Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlTypes;
using Xamarin.Forms;
using SQLite;
using System.IO;
namespace LoginPage.Views
{
public class AddDetails : ContentPage
{
private Entry _emailEntry;
private Entry _passwordEntry;
private Button _saveButton;
string _dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "myDB.db3");
public AddDetails()
{
this.Title = "Add Details";
StackLayout stackLayout = new StackLayout();
_emailEntry = new Entry();
_emailEntry.Keyboard = Keyboard.Text;
_emailEntry.Placeholder = "Email";
stackLayout.Children.Add(_emailEntry);
_passwordEntry = new Entry();
_passwordEntry.Keyboard = Keyboard.Text;
_passwordEntry.Placeholder = "Password";
stackLayout.Children.Add(_passwordEntry);
_saveButton = new Button();
_saveButton.Text = "Login User";
_saveButton.Clicked += _saveButton_Clicked;
stackLayout.Children.Add(_saveButton);
Content = stackLayout;
}
private async void _saveButton_Clicked(object Sender, EventArgs e)
{
var db = new SQLiteConnection(_dbPath);
db.CreateTable<User>();
var maxPk = db.Table<User>().OrderByDescending(c => c.Id).FirstOrDefault();
User user = new User()
{
Id = (maxPk == null ? 1 : Convert.ToInt32(maxPk.Id) +1),
Email = _emailEntry.Text,
Password = _passwordEntry.Text
};
db.Insert(user);
await DisplayAlert(null, user.Email + "Saved", "Ok");
await Navigation.PopAsync();
}
}
}
Login screen gets displayed, but no alert box which should say Email saved. Also, it comes out of the app abruptly
Have you set
MainPage = new NavigationPage (new Page1Xaml ());
Please follow this link
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/navigation/
I am trying to learn GTK# (obviously in C#). I am using Ubuntu and I compile with mono. I want to create a MenuBar and add some Menu, and MenuItem to it.
When I compile, all is OK but my menu isn't displaying.
public MainWindow() : base("LayText")
{
SetDefaultSize(800, 600);
SetPosition(WindowPosition.Center);
DeleteEvent += delegate { Application.Quit(); };
this.InitializeComponent();
ShowAll();
}
private void InitializeComponent()
{
this.m_new = new MenuItem("Nouveau fichier");
this.m_open = new MenuItem("Ouvrir fichier");
this.m_exit = new MenuItem("Quitter");
this.file = new Menu();
this.file.Append(this.m_new);
this.file.Append(this.m_open);
this.file.Append(this.m_exit);
this.menu_file = new MenuItem("Fichier");
this.menu_file.Submenu = this.file;
this.menu_bar = new MenuBar();
this.menu_bar.Append(this.menu_file);
this.vbox_princ = new VBox(false, 2);
this.vbox_princ.PackStart(this.menu_bar, false, false, 0);
this.Add(this.vbox_princ);
}
When I compile this code I am getting the window but without the menu I've set.
Screenshot of the window
Thanks for helping me.
Layce17
The following code (just a modification/completion or yours) works perfectly. I see you are using Ubuntu. Though I don't use it, I think it shows the menu bar in the top status bar. Have you checked that out?
using Gtk;
namespace Kk
{
class MainWindow: Gtk.Window {
public MainWindow() : base("LayText")
{
SetDefaultSize(800, 600);
SetPosition(WindowPosition.Center);
DeleteEvent += delegate { Application.Quit(); };
this.InitializeComponent();
ShowAll();
}
private void InitializeComponent()
{
var m_new = new MenuItem("Nouveau fichier");
var m_open = new MenuItem("Ouvrir fichier");
var m_exit = new MenuItem("Quitter");
var file = new Menu();
file.Append(m_new);
file.Append(m_open);
file.Append(m_exit);
var menu_file = new MenuItem("Fichier");
menu_file.Submenu = file;
var menu_bar = new MenuBar();
menu_bar.Append(menu_file);
var vbox_princ = new VBox(false, 2);
vbox_princ.PackStart(menu_bar, false, false, 0);
this.Add(vbox_princ);
}
public static void Main()
{
Application.Init();
new MainWindow();
Application.Run();
}
}
}
Hope this helps.
I'm learning Awesomium and following is the code in which I'm trying to login to https://accounts.google.com. I'm successfully able to set the login and password field values in the page, but not able to submit the login form, neither does the click works. Can anyone help me how to login?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Awesomium.Core;
namespace Awesom
{
class Program1
{
public static void Main(String[] args)
{
Console.WriteLine("Started....");
WebView wv = WebCore.CreateWebView(1024, 600);
wv.Source = new Uri("https://accounts.google.com");
wv.LoadingFrameComplete += (s, e) =>
{
if (!e.IsMainFrame)
return;
dynamic document = (JSObject) wv.ExecuteJavascriptWithResult("document");
using(document)
{
//Works
var tbox = document.getElementById("Email");
tbox.value = "XXXXXXXX#gmail.com";
//Works
var pbox = document.getElementById("Passwd");
pbox.value = "**********";
//Doesnt work
var lform = document.getElementById("gaia_loginform");
lform.submit();
//Doesnt work
var sbox = document.getElementById("signIn");
sbox.click();
}
BitmapSurface surface = (BitmapSurface)wv.Surface;
surface.SaveToPNG("result.png", true);
WebCore.Shutdown();
};
WebCore.Run();
}
}
}
Result image:
It IS working, you're just taking the screenshot too early. You need to account for the second frame navigation, if you use .click().
public static void Main(String[] args)
{
Console.WriteLine("Started....");
WebView wv = WebCore.CreateWebView(1024, 600);
wv.Source = new Uri("https://accounts.google.com/");
FrameEventHandler handler = null;
handler = (s, e) =>
{
if (e.IsMainFrame)
{
// we have finished loading main page,
// let's unhook ourselves
wv.LoadingFrameComplete -= handler;
LoginAndTakeScreenShot(wv);
}
};
wv.LoadingFrameComplete += handler;
WebCore.Run();
}
private static void LoginAndTakeScreenShot(WebView wv)
{
dynamic document = (JSObject)wv.ExecuteJavascriptWithResult("document");
using (document)
{
//Works
var tbox = document.getElementById("Email");
tbox.value = "XXXXXXXX#gmail.com";
//Works
var pbox = document.getElementById("Passwd");
pbox.value = "**********";
FrameEventHandler handler = null;
handler = (sender, args) =>
{
if (args.IsMainFrame)
{
wv.LoadingFrameComplete -= handler;
BitmapSurface surface = (BitmapSurface)wv.Surface;
surface.SaveToPNG("result.png", true);
WebCore.Shutdown();
}
};
wv.LoadingFrameComplete += handler;
var sbox = document.getElementById("signIn");
sbox.click();
}
}
I'm a complete noob in C# programming. This is my problem: I have a form with a panel that is generated upon clicking button 1, the panel also containes a button (btnColor1) to change the backcolor of the panel. I would like to refer to the panel's backcolor in btnColor1, but I get the error "The name 'btnColor1' does not exist in the current context". How can I fix this?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TEST_APP_1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Panel myPanel1 = new Panel();
myPanel1.Location = new System.Drawing.Point(100, 50);
myPanel1.Name = "Panel 1";
myPanel1.Size = new System.Drawing.Size(200, 100);
myPanel1.BackColor = Color.Red;
TextBox textBox1 = new TextBox();
textBox1.Location = new Point(10, 50);
textBox1.Text = "empty field";
textBox1.Size = new Size(150, 30);
Button btnColor1 = new Button();
btnColor1.Location = new Point(10, 10);
btnColor1.Text = "GOLD";
btnColor1.Size = new Size(100, 30);
btnColor1.Click += myButton1_Click;
myPanel1.Controls.Add(textBox1);
myPanel1.Controls.Add(btnColor1);
Controls.Add(myPanel1);
}
private void myButton1_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
btnColor1.BackColor = Color.Gold;
}
}
}
btnColor1 is declared in the scope of the button1_Click method so does not exist as a variable to reference in your event handler. Change the event handler to this:
private void myButton1_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
(sender as Button).BackColor = Color.Gold;
}
You can try to use the parent property of the button to access the panel and the form:
private void myButton1_Click(object sender, EventArgs e)
{
Button but = (sender as Button);
but.BackColor = Color.Gold;
// this changes the color of the panel
but.Parent.BackColor = Color.Gold;
// this changes the color of the form containing the panel
if (but.Parent.Parent != null)
{
but.Parent.Parent.BackColor = Color.Gold;
}
}