UISwipeGestureRecogniser not being recognised - ios6

I have a UIScrollView into which I am creating and adding UILabels containing the results of a simple LINQ query.
I have set up a UISwipeGestureRecognizer within the loop that generates the labels (iOS: issues with UIGestureRecognisers vs Subviews says I need a new recogniser for each control - I'm assuming I can do with a UILabel the same as UIImageView for adding a recogniser) and then added the recogniser to the label.
When the view containing the UIScrollView is started, the scrollview works as expected, but the swipe isn't.
Caveat : only tried this on the simulator, my iPhone is acting up.
private void CreateViewHistory()
{
float xtext = 4f;
float y = 4f;
int c = 0;
var tv = tank.Events.OrderByDescending(t => t.Date).ToList();
tbiHistClearAll.Enabled = enableDelete;
//tgrRemove.AddTarget(this, new Selector("screenSwipe"));
//pgrRemove.DelaysTouchesBegan = true;
foreach (var e in tv)
{
var tgrRemove = new UISwipeGestureRecognizer()
{
NumberOfTouchesRequired = 1,
Direction = UISwipeGestureRecognizerDirection.Right,
};
tgrRemove.AddTarget(this, new Selector("screenSwipe"));
svHistoryEvents.PanGestureRecognizer.RequireGestureRecognizerToFail(tgrRemove);
string info = string.Format("{0} - {1}{2} ({3})\n{4} - {5}\n{6} - {7}\n{8} - {9}", e.EventType, e.Volume, AppDelegate.Self.db.getShortVolumeUnits(), e.Date.ToShortDateString(),
StringUtils.GetString("Sowcrop.Implement"), e.Implement != null ? e.Implement.ImplementType : StringUtils.GetString("Common.NonRecorded"),
StringUtils.GetString("Common.User"), StringUtils.GetString("Common.NonRecorded"),
StringUtils.GetString("Common.Notes"), !string.IsNullOrEmpty(e.Notes) ? e.Notes : StringUtils.GetString("Common.NonRecorded"));
var lbl = new UILabel()
{
UserInteractionEnabled = true
};
lbl = UICreation.MakeLabelWithTag(svHistoryEvents, new RectangleF(xtext, y, 320f, 90f), info, UITextAlignment.Left, UIColor.Black, false, 4, c);
lbl.AddGestureRecognizer(tgrRemove);
svHistoryEvents.AddSubview(lbl);
lblTemp.Add(lbl);
c++;
y += 94f;
}
UIUtils.ResizeScrollView(svHistoryEvents);
}
[Export("screenSwipe")]
public void SwipeRemove(UIGestureRecognizer s)
{
var swipe = s as UIGestureRecognizer;
var tv = tank.Events.OrderByDescending(t => t.Date).ToList();
var txt = swipe.View as UILabel;
switch (swipe.State)
{
case UIGestureRecognizerState.Began:
Console.WriteLine("Swipe began");
break;
case UIGestureRecognizerState.Changed:
Console.WriteLine("Swipe changed");
tv.RemoveAt(txt.Tag);
CreateViewHistory();
break;
case UIGestureRecognizerState.Ended:
Console.WriteLine("Swipe ended");
break;
case UIGestureRecognizerState.Cancelled:
Console.WriteLine("Swipe cancelled");
break;
}
}
MakeLabelWithTag generates a UILabel which can then be added to the scrollview.
Am I missing something here, or do I need to do something special as the label is held within a scrollview?
I've also tried what has been suggested at UISwipeGestureRecogniser in a UIScrollView, but still without success.

Found the problem and it's probably the dumbest thing I've encountered in a long time!
To get the swipe gesture to work within a scrollview, you have to first encompass whatever it is you want to add within a UIView and then add that to the scrollview.
To therefore get a swipe within a scrollview to work, you need to do the following
private void CreateViewHistory()
{
foreach (var i in svHistoryEvents.Subviews)
if (i is UIView)
i.RemoveFromSuperview();
float xtext = 4f;
float y = 4f;
int c = 0;
tbiHistClearAll.Enabled = enableDelete;
foreach (var e in tv)
{
var tgrRemove = new UISwipeGestureRecognizer()
{
NumberOfTouchesRequired = 1,
Direction = UISwipeGestureRecognizerDirection.Right,
};
tgrRemove.AddTarget(this, new Selector("screenSwipe"));
var view = new UIView(new RectangleF(xtext, y, 320f, 90f));
svHistoryEvents.PanGestureRecognizer.RequireGestureRecognizerToFail(tgrRemove);
string info = string.Format("{0} - {1}{2} ({3})\n{4} - {5}\n{6} - {7}\n{8} - {9}", e.EventType, e.Volume, AppDelegate.Self.db.getShortVolumeUnits(), e.Date.ToShortDateString(),
StringUtils.GetString("Sowcrop.Implement"), e.Implement != null ? e.Implement.ImplementType : StringUtils.GetString("Common.NonRecorded"),
StringUtils.GetString("Common.User"), StringUtils.GetString("Common.NonRecorded"),
StringUtils.GetString("Common.Notes"), !string.IsNullOrEmpty(e.Notes) ? e.Notes : StringUtils.GetString("Common.NonRecorded"));
var lbl = new UILabel()
{
UserInteractionEnabled = true
};
lbl = UICreation.MakeLabelWithTag(svHistoryEvents, new RectangleF(0, 0, 320f, 90f), info, UITextAlignment.Left, UIColor.Black, false, 4, c);
view.AddGestureRecognizer(tgrRemove);
view.AddSubview(lbl);
svHistoryEvents.AddSubview(view);
lblTemp.Add(lbl);
c++;
y += 94f;
}
UIUtils.ResizeScrollView(svHistoryEvents);
}
[Export("screenSwipe")]
public void SwipeRemove(UIGestureRecognizer s)
{
var swipe = s as UIGestureRecognizer;
var txt = swipe.View.Subviews[0] as UILabel;
switch (swipe.State)
{
case UIGestureRecognizerState.Began:
Console.WriteLine("Swipe began");
break;
case UIGestureRecognizerState.Changed:
Console.WriteLine("Swipe changed");
break;
case UIGestureRecognizerState.Ended:
Console.WriteLine("Swipe ended");
tv.RemoveAt(txt.Tag);
CreateViewHistory();
break;
case UIGestureRecognizerState.Cancelled:
Console.WriteLine("Swipe cancelled");
break;
}
}
It is not possible to add just a UILabel and have the swipe act on that, it has to be on a UIView with the label as a subview to it.

Related

Unity3D: How to go Back or Forward in Array list

I have a gameObject with an ID, the gameObjects are spawned by giving initial ID: 1 , then any after spawned will be +1 so next is ID: 2.
I have two buttons that check current gameObjects ID#, BackOneButton (-1) and PlusOneButton (+1).
Currently it works but only if the array of gameObjects have IDs in order like for example [gameObject-ID:1], [gameObject-ID:2], [gameObject-ID:3]
But since you can self destruct a certain gameObject, here is where the error is --->
Now the array is not in order for example [gameObject-ID:1], [gameObject-ID:3], [gameObject-ID:4]. So if I'm currently in [gameObject-ID:3] and I use the BackOneButton and looks for ID: 2 it won't find it BUT there is ID:1. That's my error, I can't seem to figure out how to handle this.
Basically, How do I handle missing increments and skip over the missing?
Left Button (MinusOneButton)
void ButtonAction_LeftMinusOne()
{
// Get list of all gameObjects and -1 current to switch
string objName = manager.currentObjectTransform.name;
string[] splitArray = objName.Split('_');
string idObjNumber = splitArray[1];
switch (idObjNumber)
{
case "0":
// not supposed to be ID: 0
break;
case "1":
// nothing to go back to, this is ID: 1
break;
default:
// currently in (ID: 2 & Up) second object
int currentID = int.Parse(idObjNumber);
string idBackOne = (currentID - 1).ToString();
GameObject[] allObjInFull = GameObject.FindGameObjectsWithTag("Object");
if (allObjInFull.Length >= 2)
{
for (int i = 0; i < allObjInFull.Length; i++)
{
if (allObjInFull[i].transform.name.Contains(idBackOne))
{
// Set Camera
camera.transform.parent = allObjInFull[i].transform.GetChild(0).GetChild(1);
camera.transform.position = allObjInFull[i].transform.GetChild(0).GetChild(1).position;
camera.transform.rotation = allObjInFull[i].transform.GetChild(0).GetChild(1).rotation;
}
}
}
break;
}
}
Right Button (PlusOneButton)
void ButtonAction_RightPlusOne()
{
// Get list of all objects and +1 current to switch
string objName = manager.currentObjectTransform.name;
string[] splitArray = objName.Split('_');
string idObjNumber = splitArray[1];
switch (idObjNumber)
{
case "0":
// not supposed to be ID: 0
break;
default:
// currently in (ID: 1 & Up) object
int currentID = int.Parse(idObjNumber);
string idPlusOne = (currentID + 1).ToString();
GameObject[] allObjInFull = GameObject.FindGameObjectsWithTag("Object");
if (allObjInFull.Length >= 2)
{
for (int i = 0; i < allObjInFull.Length; i++)
{
if (allObjInFull[i].transform.name.Contains(idPlusOne))
{
// Set Camera
camera.transform.parent = allObjInFull[i].transform.GetChild(0).GetChild(1);
camera.transform.position = allObjInFull[i].transform.GetChild(0).GetChild(1).position;
camera.transform.rotation = allObjInFull[i].transform.GetChild(0).GetChild(1).rotation;
}
}
}
break;
}
}
It would be way better (especially regarding maintenance) and more efficient to have a central manager class with a List<GameObject> where you simply Add and Remove items dynamically. (Since you already seem to have one in manager I would rather extend that one)
public static class ObjectsManager
{
// If you are not concerned about
// capsulation you could ofcourse make this public as well
// but I thought this is cleaner
private static List<GameObject> objects;
// Read-only property
public static int Count
{
get
{
Initialize();
return objects.Count;
}
}
// initialize the list once
// I first had this in e.g. Awake
// but now you can easily use this in multiple scenes
public static void Initialize(bool force reinitialize = false)
{
if(objects != null && ! reinitialize) return;
objects = FindObjectsWithTag("Object").ToList();
}
public static void Add(GameObject newObject)
{
Initialize();
if(objects.Contains(newObject) return;
objects.Add(newObject);
}
public static void Destroy(GameObject toDestroy)
{
Initialize();
if(objects.Contains(toDestroy)
{
objects.Remove(toDestroy);
}
Object.Destroy(toDestroy);
}
public static int IndexOf(GameObject obj)
{
Initialize();
return objects.IndexOf(obj);
}
public static GameObject GetByIndex(int index)
{
Initialize();
// Use modulo to wrap around the index in case
// +1 or -1 exceeds the list ends
// in your case you might not need it
// but I decided to add it to be more flexible
var nextIndex = (index + 1) % objects.Count;
return objects[index];
}
}
Everytime you Instantiate a new object make sure to also call
ObjectsManager.Add(newObject);
and everytime where you destroy an object rather use
ObjectsManager.Destroy(objectToDestroy);
so it is also removed from the list first.
Then you can easily use
var currentIndex = ObjectsManager.IndexOf(certainObject);
to get the current index of an object and simply move through the index (+1, -1)
var nextObject = ObjectsManager.GetByIndex(currentIndex + 1);
var lastObject = Objects manager.GetByIndex(currentIndex - 1);
In case you switch the scene you have reinitialize the list once in order to get rid of null references
ObjectsManager.Initialize(true);
In your example code you would e.g. use something like
void ButtonAction_LeftMinusOne()
{
GameObject currentObject = manager.currentObjectTransform.gameObject;
int currentIndex = ObjectsManager.IndexOf(currentObject);
if(currentIndex < 0)
{
Debug.LogErrorFormat(this, "Object {0} is not in list!", currentObject.name);
return;
}
if(currentIndex == 0)
{
// nothing to do go back to
// Except you want wrap around then simply remove this check
Debug.Log("Already is first object in list", this);
return;
}
GameObject newObject = ObjectsManager.GetByIndex(currentIndex - 1);
Transform childOfNewObject = newObject.GetChild(0).GetChild(1);
// Set Camera
// Using simply SetParent with parameter worldPositionStays=false
// reduces it to one single call
camera.transform.SetParent( childOfNewObject, false);
}
And accordingly
void ButtonAction_RightPlusOne()
{
GameObject currentObject = manager.currentObjectTransform.gameObject;
int currentIndex = ObjectsManager.IndexOf(currentObject);
if(currentIndex < 0)
{
Debug.LogErrorFormat(this, "Object {0} is not in list!", currentObject.name);
return;
}
if(currentIndex == ObjectsManager.Count - 1)
{
// nothing to do go forward to
// Except you want wrap around then simply remove this check
Debug.Log("Already is last object in list", this);
return;
}
GameObject newObject = ObjectsManager.GetByIndex(currentIndex + 1);
Transform childOfNewObject = newObject.GetChild(0).GetChild(1);
// Set Camera
// Using simply SetParent with parameter worldPositionStays=false
// reduces it to one single call
camera.transform.SetParent( childOfNewObject, false);
}

Drag and Drop Arrays AS3

I'm trying to create a drag and drop game in Actionscript 3 using mostly arrays. I'm doing it on a simpler game first before going to the main game because I need to know how the codes work first.
The simpler game is just there are two squares and two circles. The two squares are on a different array while the two circles are in the same one. What should happen is that when either circles hit (hitTestPoint) the right square, their x and y becomes the center of the square. (like it clicks to the center). And when either circles hit the left square, it should return the circles to their last position (doesn't have to be their original position).
Here's the code:
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.display.DisplayObject;
import flash.geom.Point;
import flash.events.Event;
public class MC_MAIN extends MovieClip
{
var mc1:mc_circle;
var mc2:mc_circle;
var mc3:mc_square;
var mc4:mc_square;
var Shapes:Array;
var Target:Array;
var WTarget:Array;
var newPlace:Point;
public function MC_MAIN()
{
// constructor code
init();
}
function init():void
{
Shapes = new Array ;
Target = new Array ;
WTarget = new Array ;
mc3 = new mc_square();
mc3.height = 75;
mc3.width = 75;
mc3.x = 400;
mc3.y = 200;
Target.push(mc3);
addChild(mc3);
mc4 = new mc_square();
mc4.height = 75;
mc4.width = 75;
mc4.x = 150;
mc4.y = 200;
WTarget.push(mc4);
addChild(mc4);
mc1 = new mc_circle();
mc1.height = 25;
mc1.width = 25;
mc1.x = 100;
mc1.y = 100;
Shapes.push(mc1);
addChild(mc1);
mc2 = new mc_circle();
mc2.height = 25;
mc2.width = 25;
mc2.x = 200;
mc2.y = 200;
Shapes.push(mc2);
addChild(mc2);
for (var i:int = 0; i<Shapes.length; i++)
{
Shapes[i].addEventListener(MouseEvent.MOUSE_DOWN, DRG);
Shapes[i].addEventListener(MouseEvent.MOUSE_UP, SDRG);
}
}
function DRG(e:MouseEvent):void
{
e.currentTarget.startDrag();
}
function SDRG(e:MouseEvent):void
{
e.currentTarget.stopDrag();
for (var m:int = 0; m<Shapes.length; m++)
{
newPlace = new Point(Shapes[m].x,Shapes[m].y);
}
trace(newPlace);
for (var a:int = 0; a<Target.length; a++)
{
for (var b:int = 0; b<Shapes.length; b++)
{
if (Target[a].hitTestPoint(Shapes[b].x,Shapes[b].y))
{
Shapes[b].x = Target[a].x;
Shapes[b].y = Target[a].y;
}
}
}
for (var c:int = 0; c<WTarget.length; c++)
{
for (var d:int = 0; d<Shapes.length; d++)
{
if (WTarget[c].hitTestPoint(Shapes[d].x,Shapes[d].y))
{
Shapes[d].x = newPlace.x;
Shapes[d].y = newPlace.y;
}
}
}
}
}
}
What happens is that the code for the left square doesn't work but their are no syntax errors. Nothing happens when either circles hit the left square.
And when I'm trying to trace the position of the circles, It just shows the x & y coordinate of only one of them. (I guess it's tracing the first object of the array which is at index 0. I'm just asking if I guessed right for this part.)
I is a bit difficult to follow the logic and there are some points that doesn't make much sense like:
for (var m:int = 0; m<Shapes.length; m++)
{
newPlace = new Point(Shapes[m].x,Shapes[m].y);
}
newPlace will be the position of the last shape in Shapes, so the loop is fairly useless.
I guess what you need is something like that:
public class MC_MAIN extends MovieClip
{
private leftSquares:Array;
private rightSquares:Array;
//more of the members from above
private startPos:Point;
//init the thing and add left and right squares
//to there respective Array
function DRG(e:MouseEvent):void
{
var t:DisplayObject = e.currentTarget;
//save the starting position
startPos = new Point(t.x,t.y);
t.startDrag();
}
function SDRG(e:MouseEvent):void {
var t:DisplayObject = e.currentTarget;
//find all squares from the left
//the target »hits«
var leftHits:Array = leftSquares.filter(
function (square:DisplayObject) {
return square.hitTestPoint(t.x, t.y);
});
//same for the right
var leftHits:Array = rightSquares.filter(
function (square:DisplayObject) {
return square.hitTestPoint(t.x, t.y);
});
//now you can apply the logic
//based on the hit Test result
//this way you can handle the case
//if it hits both, to throw an error
//or alike
if(leftHits.length > 0) {
//reset position
t.x = startPos.x;
t.y = startPos.y;
}
else if (rightHits.length > 0) {
//set the position tp the desired item in rightHits
}
else {
}
}
}
Please not that my Action Script skills haven't been used for a long time, so the code above might not compile. It is meant to illustrate the idea. Important are the following steps:
1. Save the starting position, to be able to reset it
2. Sort the `squares` in respective lists for left and right
3. Hit test both and apply the logic.

dropdown error on device in codenameone

I am implementing drop-drown feature in my app. Its implemented using container with list of elements in it.
Suppose the drop down list has following items aa1, aa2, aa3, aa4 aa5 and so on. And if i search as 'aa' it displays items starting from 'aa', if I select aa5 from list, it takes aa1 and displays that. But whereas if I scroll the items and select its working fine. This problem occurring only on iOS device working perfectly fine on simulator.
the first picture depicts how drop down looks like, in second picture if I search 'ee', it gives list of items starting with 'ee'. If I select 'ee5', it sets to ee1 as shown in picture 3. Problem only on device. Any workaround for this?
So, please let me know whats the issue with this.
Thanks
[![enter image description here][1]][1]
private CustomList itemList;
class CustomList extends List {
int startYPos = -1;
long lastDiff = 0;
Timer t = null;
int draggingState = 0;
public CustomList() {
this.setTensileDragEnabled(false);
}
}
private class ButtonListener implements ActionListener {
public void actionPerformed(final ActionEvent evt) {
final Runnable rn = new Runnable() {
public void run() {
// Create and show a dialog to allow users to make a selection.
final UiBuilder uib = dm.UiBuilder();
dialog = (Dialog) uib.createContainer(DESIGNER_NAME_DIALOG_COMBOBOX_CONTAINER);
GenericSpinner itemSpinner = (GenericSpinner) uib.findByName(DESIGNER_NAME_DIALOG_COMBOBOX_GENERIC_SPINNER, dialog);
itemSpinner.setPreferredW(Display.getInstance().getDisplayWidth() * 4 / 5);
//remove from parent and replace with a linear list
Container parent = itemSpinner.getParent();
parent.removeComponent(itemSpinner);
// Add the searchable text field box
final TextField tf = (TextField)uib.findByName("Search", dialog);
tf.addDataChangedListener(new DataChangedListener() {
#Override
public void dataChanged(int type, int index) {
Object[] items = model.getFilteredItems(tf.getText());
itemList.setModel(new DefaultListModel(items));
}
});
itemList = new CustomList();
itemList.getAllStyles().setBgTransparency(0);
itemList.setItemGap(0);
parent.addComponent(BorderLayout.CENTER, itemList);
final String[] items = model.getItems();
itemList.setModel(new DefaultListModel(items));
itemList.getStyle().setMargin(10, 10, 10, 10);
itemList.setFireOnClick(true);
itemList.setLongPointerPressActionEnabled(false);
ActionListener list = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (model.isUserEditable() && model.getItemCount() > 0) {
int i = itemList.getSelectedIndex();
if (i > items.length - 1) {
return;
}
itemList.getModel().setSelectedIndex(i);
model.onUserDataEntered((String) itemList.getModel().getItemAt(i));
String textToDisplay = (String) itemList.getModel().getItemAt(i);
button.setText(textToDisplay);
}
dialog.dispose();
}
};
itemList.addActionListener(list);
CommonTransitions tran = CommonTransitions.createEmpty();
dialog.setTransitionInAnimator(tran);
dialog.setTransitionOutAnimator(tran);
itemList.setRenderer(new ListRenderer());
//related to dialog to show list of items
//how much space do we really need???
if (cellHeight == 0) {
int dip = Display.getInstance().convertToPixels(1);
int siz = 2;
if (Display.getInstance().isTablet()) {
siz = 4;
}
siz *= 2;
cellHeight = siz * dip;
}
int heightRequired = cellHeight * (items.length + 8);
//is this too much for the screen - we will use 3/4 of the screen height max
int availableHeight = Display.getInstance().getDisplayHeight() * 3;
availableHeight /= 4;
if (heightRequired > availableHeight) {
int topPos = Display.getInstance().getDisplayHeight() / 8;
int bottomPos = topPos + availableHeight;
dialog.show(topPos, topPos, 40, 40);
}
else {
int topPos = (Display.getInstance().getDisplayHeight() - heightRequired) / 2;
int bottomPos = topPos + heightRequired;
dialog.show(topPos, topPos, 40, 40);
}
}
};
}
}
//new code using Multibutton implementation
final String[] listItems = model.getItems();
Display.getInstance().callSerially(() ->{
multiButton= new MultiButton();
multiButton.setTextLine1(s);
dialog.add(multiButton);
multiButton.addActionListener(e -> Log.p("you picked " + multiButton.getSelectCommandText(), Log.ERROR));
}
dialog.revalidate();
});
I would recommend using a Container and simple layout search as demonstrated by code such as this. The code below was taken from the Toolbar javadoc:
Image duke = null;
try {
duke = Image.createImage("/duke.png");
} catch(IOException err) {
Log.e(err);
}
int fiveMM = Display.getInstance().convertToPixels(5);
final Image finalDuke = duke.scaledWidth(fiveMM);
Toolbar.setGlobalToolbar(true);
Form hi = new Form("Search", BoxLayout.y());
hi.add(new InfiniteProgress());
Display.getInstance().scheduleBackgroundTask(()-> {
// this will take a while...
Contact[] cnts = Display.getInstance().getAllContacts(true, true, true, true, false, false);
Display.getInstance().callSerially(() -> {
hi.removeAll();
for(Contact c : cnts) {
MultiButton m = new MultiButton();
m.setTextLine1(c.getDisplayName());
m.setTextLine2(c.getPrimaryPhoneNumber());
Image pic = c.getPhoto();
if(pic != null) {
m.setIcon(fill(pic, finalDuke.getWidth(), finalDuke.getHeight()));
} else {
m.setIcon(finalDuke);
}
hi.add(m);
}
hi.revalidate();
});
});
hi.getToolbar().addSearchCommand(e -> {
String text = (String)e.getSource();
if(text == null || text.length() == 0) {
// clear search
for(Component cmp : hi.getContentPane()) {
cmp.setHidden(false);
cmp.setVisible(true);
}
hi.getContentPane().animateLayout(150);
} else {
text = text.toLowerCase();
for(Component cmp : hi.getContentPane()) {
MultiButton mb = (MultiButton)cmp;
String line1 = mb.getTextLine1();
String line2 = mb.getTextLine2();
boolean show = line1 != null && line1.toLowerCase().indexOf(text) > -1 ||
line2 != null && line2.toLowerCase().indexOf(text) > -1;
mb.setHidden(!show);
mb.setVisible(show);
}
hi.getContentPane().animateLayout(150);
}
}, 4);
hi.show();

Microsoft speech recognizer stops recognizing

I am having trouble with the Microsoft speech recognizer. I am trying to make it constantly listen to me, and only after the word HELLO is recognized, it shows what I said. This part appears to be working, but after 15-20 seconds as the object "sre" is destroyed (as i think) the recognizer stops responding.
static void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
List<string> words = new List<string>();
int count = e.Result.Words.Count;
for (int i = 0; i < count; i++)
{
words.Add(e.Result.Words[i].Text);
}
if (e.Result.Confidence > 0.7)
{
if (words[0].ToString() == "Hello")
{
switch (count)
{
case 2:
t.Text = words[1];
break;
case 3:
t.Text = words[1] + " " + words[2];
break;
}
}
}
}
private void InitializeSpeechGrammar()
{
t = UserMessage;
SpeechRecognitionEngine sre= new SpeechRecognitionEngine();
sre.SetInputToDefaultAudioDevice();
sre.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized);
var grammarBuilder = new GrammarBuilder();
grammarBuilder.Append(new Choices("Hello"));
grammarBuilder.AppendWildcard();
sre.BabbleTimeout = TimeSpan.FromSeconds(3);
sre.InitialSilenceTimeout = TimeSpan.FromSeconds(3);
var CommToRecognize = new Choices();
CommToRecognize.Add(new string[] { "Red", "Green", "Blue", "Yellow", "Grey" });
grammarBuilder.Append(CommToRecognize);
Grammar g = new Grammar(grammarBuilder);
sre.LoadGrammar(g);
sre.RecognizeAsync(RecognizeMode.Multiple);
}
So, there is the RecognizeMode.Multiple mode:
sre.RecognizeAsync(RecognizeMode.Multiple);
Should I be using this mode instead? Or is there something else that I am doing wrong?

Codenameone Tensile Drag Issue

I am trying to get rid of the tensile drag for scrolling a Container with a BoxY Layout.
Code:
f.setScrollable(false);
appendExit(f);
String form_uuid = "";
Container tlist = new Container(new BoxLayout(BoxLayout.Y_AXIS));
tlist.setScrollableY(false);
tlist.setTensileDragEnabled(false);
Container tocCntn = new Container(new BoxLayout(BoxLayout.Y_AXIS));
tlist.setUIID("toc");
BorderLayout bl = new BorderLayout();
bl.setCenterBehavior(BorderLayout.CENTER_BEHAVIOR_CENTER_ABSOLUTE);
Container tocH = new Container(bl);
Label lic = new Label(AppState.res.getImage("Menu_Icon.png"));
lic.setUIID("Container");
lic.getStyle().setMargin(Component.LEFT, 10);
tocH.addComponent(BorderLayout.WEST, lic);
Label l_h = new Label("Contents");
l_h.setUIID("typelabel");
tocH.addComponent(BorderLayout.CENTER, l_h);
tlist.addComponent(tocH);
TopicParser parser = new TopicParser();
switch (AppState.topic_type) {
case 1:
AppState.typelabel = "Listening Skills";
form_uuid = "lbg";
AppState.icon = AppState.res.getImage("licon.png");
brandface = AppState.res.getImage("list_girl.png");
AppState.current_topics = parser.parse(AppState.l_topics);
tocH.setUIID("ltoc");
break;
case 2:
AppState.typelabel = "Speaking Skills";
form_uuid = "rbg";
brandface = AppState.res.getImage("speak_girl.png");
AppState.icon = AppState.res.getImage("sicon.png");
AppState.current_topics = parser.parse(AppState.s_topics);
tocH.setUIID("stoc");
break;
case 3:
AppState.typelabel = "Reading Skills";
form_uuid = "rbg";
AppState.icon = AppState.res.getImage("ricon.png");
brandface = AppState.res.getImage("reading_boy.png");
AppState.current_topics = parser.parse(AppState.r_topics);
tocH.setUIID("rtoc");
break;
case 4:
AppState.typelabel = "Writing Skills";
form_uuid = "rbg";
brandface = AppState.res.getImage("writing_girl.png");
AppState.icon = AppState.res.getImage("wicon.png");
AppState.current_topics = parser.parse(AppState.w_topics);
tocH.setUIID("wtoc");
break;
}
int i = 0;
for (final Topic topic : AppState.current_topics) {
i++;
Container topicC = new Container(new BoxLayout(BoxLayout.Y_AXIS));
//topicC.setUIID("wbg");
if (topic.getTopic_name().trim().equals("")) {
Label l = new Label(" ");
l.setUIID("toclbl");
topicC.addComponent(l);
} else {
Button topicB = new Button(i + ". " + topic.getTopic_name());
topicB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
AppState.current_topic = topic;
showForm("player", null);
}
});
topicB.setUIID("toclbl");
topicC.addComponent(topicB);
}
tocCntn.addComponent(topicC);
}
tocCntn.setScrollableY(true);
tocCntn.setScrollVisible(false);
tocCntn.setTensileDragEnabled(false);
tlist.addComponent(tocCntn);
f.addComponent(BorderLayout.CENTER, tlist);
findTypename(f).setText(AppState.typelabel);
findTypeiconimg(f).setIcon(AppState.icon);
f.setGlassPane(new Painter() {
public void paint(Graphics g, Rectangle rect) {
g.drawImage(brandface, f.getLayoutWidth()-brandface.getWidth(), f.getLayoutHeight()-brandface.getHeight()-findTopicFooter(f).getLayoutHeight());
}
});
However it doesnt seem to work.
Is there any other way to achieve this ?
Is there a way to change the color of the scroll bar
setTensileDragEnabled should do the trick, I assume you are seeing the tensile drag of the Form itself rather then your tocCntn Container.
Try this:
Form f = new Form();
f.setLayout(new BorderLayout());
f.setScrollable(false);
Container cnt = new Container(new BoxLayout(BoxLayout.Y_AXIS));
cnt.setScrollableY(true);
cnt.setTensileDragEnabled(false);
//add Components to the cnt Container
...
f.addComponent(BorderLayout.CENTER, cnt);
f.show();
UIManager.getInstance().getLookAndFeel().setDefaultTensileDrag(false);
did the trick

Resources