RichEditBox How to know Which line the cursor is in - win-universal-app

How can i know If user click Enter in keyboard in RichEditBox?
this code does not work
private void Editor_KeyDown(object sender, KeyRoutedEventArgs e)
{
var dia = new MessageDialog(e.Key + "");
dia.ShowAsync();
}
also This code does not work
private void Editor_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.OriginalKey == (VirtualKey)(char)13)
{
NumberEditor.Text += Convert.ToString(_LineNum) + Environment.NewLine;
++_LineNum;
}
}
How can i get line of row in RichEditBox and how can i change text from code in RichEditBox?
I want to make an Editor and any help is appreciated.
Regards

Look this method:
private void ChangeLine()
{
var textRange = MyRichEditBox.Document.GetRange(MyRichEditBox.Document.Selection.StartPosition, MyRichEditBox.Document.Selection.StartPosition);
textRange.Expand(TextRangeUnit.Line);
//Change line size.
textRange.CharacterFormat.Size = 30;
//Center the paragraph
textRange.ParagraphFormat.Alignment = ParagraphAlignment.Center;
//this will change text of the range
textRange.Text = "My new text";
}
From Document you have to get ITextRange. After that you can expand it to TextRangeUnit.Line and get whole line. Now you can change the style and text of the line.
Try this code for KeyDownEvent:
public sealed partial class TextEditPage : Page
{
private readonly KeyEventHandler _keyDownHandler;
//Constructor
public TextEditPage()
{
this.InitializeComponent();
this.Unloaded += OnUnloaded;
//Add keydown event
this._keyDownHandler = OnKeyDown;
RtfBox.AddHandler(KeyDownEvent, this._keyDownHandler, true);
}
private void OnKeyDown(KeyRoutedEventArgs e)
{
//enter your code here
}
private void OnUnloaded(object sender, RoutedEventArgs routedEventArgs)
{
this.RemoveHandler(KeyDownEvent, _keyDownHandler);
}
}
Don't forget to remove handler in Unloaded.

Related

Recognizing multiple keyphrases in CMUSphinx for Android [duplicate]

I've installed the PocketSphinx demo and it works fine under Ubuntu and Eclipse, but despite trying I can't work out how I would add recognition of multiple words.
All I want is for the code to recognize single words, which I can then switch() within the code, e.g. "up", "down", "left", "right". I don't want to recognize sentences, just single words.
Any help on this would be grateful. I have spotted other users' having similar problems but nobody knows the answer so far.
One thing which is baffling me is why do we need to use the "wakeup" constant at all?
private static final String KWS_SEARCH = "wakeup";
private static final String KEYPHRASE = "oh mighty computer";
.
.
.
recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);
What has wakeup got to do with anything?
I have made some progress (?) : Using addGrammarSearch I am able to use a .gram file to list my words, e.g. up,down,left,right,forwards,backwards, which seems to work well if all I say are those particular words. However, any other words will cause the system to match what is said to the "nearest" word from those stated. Ideally I don't want recognition to occur if words spoken are not in the .gram file...
Thanks to Nikolay's tip (see his answer above), I have developed the following code which works fine, and does not recognize words unless they're on the list. You can copy and paste this directly over the main class in the PocketSphinxDemo code:
public class PocketSphinxActivity extends Activity implements RecognitionListener
{
private static final String DIGITS_SEARCH = "digits";
private SpeechRecognizer recognizer;
#Override
public void onCreate(Bundle state)
{
super.onCreate(state);
setContentView(R.layout.main);
((TextView) findViewById(R.id.caption_text)).setText("Preparing the recognizer");
try
{
Assets assets = new Assets(PocketSphinxActivity.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
}
catch (IOException e)
{
// oops
}
((TextView) findViewById(R.id.caption_text)).setText("Say up, down, left, right, forwards, backwards");
reset();
}
#Override
public void onPartialResult(Hypothesis hypothesis)
{
}
#Override
public void onResult(Hypothesis hypothesis)
{
((TextView) findViewById(R.id.result_text)).setText("");
if (hypothesis != null)
{
String text = hypothesis.getHypstr();
makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBeginningOfSpeech()
{
}
#Override
public void onEndOfSpeech()
{
reset();
}
private void setupRecognizer(File assetsDir)
{
File modelsDir = new File(assetsDir, "models");
recognizer = defaultSetup().setAcousticModel(new File(modelsDir, "hmm/en-us-semi"))
.setDictionary(new File(modelsDir, "dict/cmu07a.dic"))
.setRawLogDir(assetsDir).setKeywordThreshold(1e-20f)
.getRecognizer();
recognizer.addListener(this);
File digitsGrammar = new File(modelsDir, "grammar/digits.gram");
recognizer.addKeywordSearch(DIGITS_SEARCH, digitsGrammar);
}
private void reset()
{
recognizer.stop();
recognizer.startListening(DIGITS_SEARCH);
}
}
Your digits.gram file should be something like:
up /1e-1/
down /1e-1/
left /1e-1/
right /1e-1/
forwards /1e-1/
backwards /1e-1/
You should experiment with the thresholds within the double slashes // for performance, where 1e-1 represents 0.1 (I think). I think the maximum is 1.0.
And it's 5.30pm so I can stop working now. Result.
you can use addKeywordSearch which uses to file with keyphrases. One phrase per line with threshold for each phrase in //, for example
up /1.0/
down /1.0/
left /1.0/
right /1.0/
forwards /1e-1/
Threshold must be selected to avoid false alarms.
Working on updating Antinous amendment to the PocketSphinx demo to allow it to run on Android Studio. This is what I have so far,
//Note: change MainActivity to PocketSphinxActivity for demo use...
public class MainActivity extends Activity implements RecognitionListener {
private static final String DIGITS_SEARCH = "digits";
private SpeechRecognizer recognizer;
/* Used to handle permission request */
private static final int PERMISSIONS_REQUEST_RECORD_AUDIO = 1;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.main);
((TextView) findViewById(R.id.caption_text))
.setText("Preparing the recognizer");
// Check if user has given permission to record audio
int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, PERMISSIONS_REQUEST_RECORD_AUDIO);
return;
}
new AsyncTask<Void, Void, Exception>() {
#Override
protected Exception doInBackground(Void... params) {
try {
Assets assets = new Assets(MainActivity.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
} catch (IOException e) {
return e;
}
return null;
}
#Override
protected void onPostExecute(Exception result) {
if (result != null) {
((TextView) findViewById(R.id.caption_text))
.setText("Failed to init recognizer " + result);
} else {
reset();
}
}
}.execute();
((TextView) findViewById(R.id.caption_text)).setText("Say one, two, three, four, five, six...");
}
/**
* In partial result we get quick updates about current hypothesis. In
* keyword spotting mode we can react here, in other modes we need to wait
* for final result in onResult.
*/
#Override
public void onPartialResult(Hypothesis hypothesis) {
if (hypothesis == null) {
return;
} else if (hypothesis != null) {
if (recognizer != null) {
//recognizer.rapidSphinxPartialResult(hypothesis.getHypstr());
String text = hypothesis.getHypstr();
if (text.equals(DIGITS_SEARCH)) {
recognizer.cancel();
performAction();
recognizer.startListening(DIGITS_SEARCH);
}else{
//Toast.makeText(getApplicationContext(),"Partial result = " +text,Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onResult(Hypothesis hypothesis) {
((TextView) findViewById(R.id.result_text)).setText("");
if (hypothesis != null) {
String text = hypothesis.getHypstr();
makeText(getApplicationContext(), "Hypothesis" +text, Toast.LENGTH_SHORT).show();
}else if(hypothesis == null){
makeText(getApplicationContext(), "hypothesis = null", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onDestroy() {
super.onDestroy();
recognizer.cancel();
recognizer.shutdown();
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onEndOfSpeech() {
reset();
}
#Override
public void onTimeout() {
}
private void setupRecognizer(File assetsDir) throws IOException {
// The recognizer can be configured to perform multiple searches
// of different kind and switch between them
recognizer = defaultSetup()
.setAcousticModel(new File(assetsDir, "en-us-ptm"))
.setDictionary(new File(assetsDir, "cmudict-en-us.dict"))
// .setRawLogDir(assetsDir).setKeywordThreshold(1e-20f)
.getRecognizer();
recognizer.addListener(this);
File digitsGrammar = new File(assetsDir, "digits.gram");
recognizer.addKeywordSearch(DIGITS_SEARCH, digitsGrammar);
}
private void reset(){
recognizer.stop();
recognizer.startListening(DIGITS_SEARCH);
}
#Override
public void onError(Exception error) {
((TextView) findViewById(R.id.caption_text)).setText(error.getMessage());
}
public void performAction() {
// do here whatever you want
makeText(getApplicationContext(), "performAction done... ", Toast.LENGTH_SHORT).show();
}
}
Caveat emptor: this is a work in progress. Check back later. Suggestions would be appreciated.

Xamarin Button Command with Keyboard Open

I am working on an Xamarin.Forms project specifically for the iOS platform. I have an Editor control and a Button control next to each other. When I focus the editor, enter some text, and click the button it appears the command is not being fired but rather the keyboard is simply closing. I then have to tap the add button again for the command to be fired.
<StackLayout Orientation="Horizontal">
<Editor HorizontalOptions="FillAndExpand"
Text="{Binding EditorText}"/>
<Button Text="Add"
Command="{Binding AddCommand}"/>
</StackLayout>
I have tried creating a custom renderer that prevents the keyboard from closing initially and then close it after a delay. That allows the command to be fired, but I am stuck with the keyboard being open.
public class KeyboardEditorRenderer : EditorRenderer
{
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == VisualElement.IsFocusedProperty.PropertyName)
{
if (Control != null)
{
Control.ShouldEndEditing = (UITextView textField) =>
{
Task.Delay(10).ContinueWith(_ =>
{
// THIS DOES NOT WORK
textField.EndEditing(true);
});
return false;
};
}
}
base.OnElementPropertyChanged(sender, e);
}
}
My ideal solution is that you are able to enter text, tap the add button, and the keyboard closes and the command executes simultaneously. Any ideas on how to achieve this?
EDIT: It turns out the problem is with the custom renderer I use for the page. The custom renderer resizes the page when the keyboard appears so that it does not cover my editor field.
public class KeyboardPageRenderer : PageRenderer
{
private bool keyboardShowing;
private NSObject keyboardWillShow;
private NSObject keyboardWillHide;
private double duration;
private UIViewAnimationCurve curve;
public override void ViewDidLoad()
{
base.ViewDidLoad();
this.keyboardWillShow = UIKeyboard.Notifications.ObserveWillShow(this.KeyboardWillShow);
this.keyboardWillHide = UIKeyboard.Notifications.ObserveWillHide(this.KeyboardWillHide);
}
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
this.keyboardWillShow.Dispose();
this.keyboardWillHide.Dispose();
}
private void KeyboardWillShow(object sender, UIKeyboardEventArgs args)
{
if (!this.keyboardShowing)
{
this.keyboardShowing = true;
var keyboardFrame = UIKeyboard.FrameBeginFromNotification(args.Notification);
this.duration = args.AnimationDuration;
this.curve = args.AnimationCurve;
this.ScrollTheView(true, keyboardFrame.Height);
}
}
private void KeyboardWillHide(object sender, UIKeyboardEventArgs args)
{
if (this.keyboardShowing)
{
this.keyboardShowing = false;
var keyboardFrame = UIKeyboard.FrameBeginFromNotification(args.Notification);
this.duration = args.AnimationDuration;
this.curve = args.AnimationCurve;
this.ScrollTheView(false, keyboardFrame.Height);
}
}
private void ScrollTheView(bool scale, nfloat scrollAmount)
{
UIView.BeginAnimations(string.Empty, IntPtr.Zero);
UIView.SetAnimationDuration(this.duration);
UIView.SetAnimationCurve(this.curve);
var frame = View.Frame;
// Assumes the page belongs to a tabbed view.
// This does not scale to pages that do not have one.
UITabBarController tabBarController = new UITabBarController();
nfloat tabHeight = tabBarController.TabBar.Frame.Size.Height;
scrollAmount -= tabHeight;
if (scale)
{
frame.Y -= scrollAmount;
}
else
{
frame.Y += scrollAmount;
}
View.Frame = frame;
UIView.CommitAnimations();
}
}
There is two issues in your approach
After Task.Delay(10), you are not on the UI thread anymore, which means you have to use Device.BeginInvokeOnMainThread in order to access UI elements.
Control.ShouldEndEditing must be cleared before you call EndEditing
A working solution would look like this:
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (Element == null || Control == null)
return;
VisualElement element = Element as VisualElement;
if (element == null)
return;
if (e.PropertyName == VisualElement.IsFocusedProperty.PropertyName && element.IsFocused == false)
{
Control.ShouldEndEditing = (UITextView control) =>
{
Device.BeginInvokeOnMainThread(() =>
{
control.ShouldEndEditing = null;
control.EndEditing(true);
});
// prevent the keyboard from closing
return false;
};
}
}

How can I call this method using a button?

public static bool WriteBeamDataToFile(string Filename, List<Part> Parts)
{
// Open a Streamwriter to write data to the specified Filename
using (StreamWriter TeklaDataWriter = new StreamWriter(Filename))
{
// Connect to the Currently Open Tekla Model
Model Model = new Model();
foreach (Part CurrentPart in Parts)
{
if (CurrentPart != null)
{
string Name = CurrentPart.Name;
string Profile = CurrentPart.Profile.ProfileString;
string Material = CurrentPart.Material.MaterialString;
string Finish = CurrentPart.Finish;
TeklaDataWriter.WriteLine(Name + "," + Profile + "," + Material + "," + Finish);
}
}
}
return File.Exists(Filename);
}
Example:
private void button1_Click(object sender, EventArgs e)
{
How to call above method here?
}
private void button1_Click(object sender, EventArgs e) {
private bool isFileExists;
List<Parts> partsList = new List<Parts>();
isFileExists = WriteBeamDataToFile("example.txt",partsList)
if(isFileExists){
//do something..
}
}
Method above is mark as static. That's why you faced some issue.
Static method could be call from Class it' self.
While non static methods could be called from class instance.
See example:
class MyClass {
//static method
public static void Method1() {}
//non static method
public void Method2() {}
}
class MyForm:Form {
...
private void button1_Click(object sender, EventArgs e)
{
//here we call static method of MyClass
MyClass.Method1();
}
//or
private void button1_Click(object sender, EventArgs e)
{
// Here we create an instance of MyClass
var class = new MyClass();
// and call non static Method
class.Method2();
}
}
}

Cannot properly set visible component

I'm trying to implement Menu with select box which sets to display or not component. I have this checkbox:
final CheckMenuItem toolbarSubMenuNavigation = new CheckMenuItem("Navigation");
toolbarSubMenuNavigation.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent e)
{
DataTabs.renderTab = toolbarSubMenuNavigation.isSelected();
// call here the getter setter and send boolean flag
System.out.println("subsystem1 #1 Enabled!");
}
});
And I have this tabpane which I want to render only if I have selected the checkbox:
public static boolean renderTab;
public DataTabs()
{
}
public boolean isRenderTab()
{
return renderTab;
}
public void setRenderTab(boolean renderTab)
{
this.renderTab = renderTab;
}
// below this code
tabPane.setVisible(renderTab);
When I run the code it's not working. I also tested this:
DataTabs tabs = new DataTabs(); // instantiate first
tabs.setRenderTab(toolbarSubMenuNavigation.isSelected());
public static boolean renderTab;
TabPane tabPane = new TabPane();
public DataTabs()
{
}
public boolean isRenderTab()
{
return renderTab;
}
public void setRenderTab(boolean renderTab)
{
tabPane.setVisible(renderTab);
}
But again there is no result when I run the code and I check or uncheck the checkbox.
This is the complete source code:
http://pastebin.com/tkj4Fby1
Maybe I need to add listener or something else which I'm missing?
EDIT
Test 3
I also tested this code:
final CheckMenuItem toolbarSubMenuNavigation = new CheckMenuItem("Navigation");
toolbarSubMenuNavigation.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent e)
{
DataTabs.toolbarSubMenuNavigation = toolbarSubMenuNavigation;
// call here the getter setter and send boolean flag
System.out.println("subsystem1 #1 Enabled!");
}
});
// class with tabs
public static CheckMenuItem toolbarSubMenuNavigation;
public static CheckMenuItem getToolbarSubMenuNavigation()
{
return toolbarSubMenuNavigation;
}
public static void setToolbarSubMenuNavigation(CheckMenuItem toolbarSubMenuNavigation)
{
DataTabs.toolbarSubMenuNavigation = toolbarSubMenuNavigation;
}
// below
abPane.visibleProperty().bind(toolbarSubMenuNavigation.selectedProperty());
I get NPE when I run the code.
You can easely tell to your tab to be visible when you check the box in one line
yourTab.visibleProperty().bind(yourCheckBox.selectedProperty());
And just with this line your tabpane will be visible only when it's checked

How to work with LWUIT TABs click events

UPDATE:
My Requirement is to display two Rss files as Tabs on my LWUIT Form
Initially by default first Rss file titles and images should be displayed on first tab
if an end user click on second tab,we should be able to load the second rss file titles and images
I am able to load first Rss File titles,but i am not able to load the second tab if i click on it
How to capture the click event for LWUIT Tab?
Here my code which is not working:
String topNewsurl="TopNews.rss";
String topStoryurl="TopStory.rss";
public class XMLMidlet extends MIDlet{
public void startApp() {
Display.init(this);
Process p;
try {
p = new Process(this);
p.process();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public class Process extends Form {
Process(XMLMidlet midlet) throws IOException {
this.midlet=midlet;
topnews = new Vector();
topstory = new Vector();
tabs = new Tabs();
form1 = new Form();
form2=new Form();
form1.setLayout(new BorderLayout());
form1.setScrollable(false);
image = Image.createImage("/res/Tone.jpg");
Label icon = new Label(image);
form1.setTitleComponent(icon);
form2.setTitleComponent(icon);
form1.setTransitionInAnimator(Transition3D.createRotation(250, true));
try {
newsList = new List(topnews);
newsList.setScrollVisible(false);
newsList.setRenderer(new NewsListCellRenderer());
myNewsList = new List(topstory);
myNewsList.setScrollVisible(false);
myNewsList.setRenderer(new NewsListCellRenderer());
tabs.addTab("Topstory", newsList);
tabs.addTab("TopNews", myNewsList);
tabs.setChangeTabOnFocus(true);
form1.addComponent(BorderLayout.CENTER, tabs);
}
try{
String url = "http:topnews-20.rss";
form1.show();
ParseThread myThread = new ParseThread(this);
myThread.getXMLFeed(url);
} catch (Exception e) {
e.printStackTrace();
}
}
public void addNews(News newsItem) {
//log.debug("addnews");
//System.out.println("addNews");
topnews.addElement(newsItem);
newsList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
List source = (List) ae.getSource();
News selectedNewsItem = (News) source.getSelectedItem();
if (selectedNewsItem != null) {
displayCompleteNewsScreen(selectedNewsItem);
}
}
});
form1.show();
}
public void keyReleased(int keyCode) {
System.out.println("str");
Component p=this.getFocused();
String str= p.getClass().getName();
if(str.toLowerCase().indexOf("radiobutton")!=-1){
process();
}
From the very vague question it seems you want to capture key presses on a LWUIT Form.
jobsForm.addGameKeyListener(Display.GAME_FIRE,
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//do something here
}
});
jobsForm.addPointerPressedListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
pointer_click = true;
}
});
jobsForm.addPointerReleasedListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (pointer_click) {
//
}
pointer_click = false;
}
});
jobsForm.addPointerDraggedListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//System.out.println("POINTER DRAGGED");
pointer_click = false;
}
});

Resources