I have a script that currently displays dialogue text letter by letter. Currently it rolls through each string of text in my _stanzas array without pausing. I would like to change this script so that it requires the user to press "Z" on their keyboard before the script begins to print the next block of text from _stanzas. I cant seem to figure it out...here is my code.
using UnityEngine;
using System.Collections;
public class Text : MonoBehaviour {
public float LetterPause = 0.1f;
public GameObject text;
public GameObject box;
public GameObject name;
private bool _textFinished;
private int _textIndex;
private string[] _stanzas;
int tracker;
public void Start()
{
if (Application.loadedLevel == 1) {
_stanzas = new [] {
" It’s Terrence’s hat... ",
"He always was one to lose track of the" + "\n" + "material objects in life," + "\n" + "but to hold onto the immaterial forever.",
"I’ll carry it for him" + "\n" + "until I find him. "
};
}
_textFinished = true;
_textIndex = -1;
tracker = _textIndex;
}
public void Update()
{
if (_textFinished)
{
if (_textIndex++ >= (_stanzas.Length - 1))
{
_textFinished = false;
text.SetActive(false);
box.SetActive(false);
name.SetActive(false);
}
if (_textFinished){
SetText(_stanzas[_textIndex]);}
}
}
private IEnumerator TypeText(float waitTime, string text)
{
_textFinished = false;
guiText.text = "";
foreach (var letter in text)
{
guiText.text += letter;
yield return new WaitForSeconds (waitTime);
}
_textFinished = true;
}
private void SetText(string text)
{
StartCoroutine(TypeText(LetterPause, text));
}
}
change
if (_textFinished)
to
if (_textFinished && (Input.GetKeyDown(KeyCode.Z) || _textIndex < 0))
Related
recently I started learning Java, I watched a YT video where a programmer used static methods and variables to create a simple guess game using JFrame.
Afterwards I tried to implement a close/restart button, after reading some Threads I relized static methods aren´t made that for. So my question is now how do I solve my problem now. :)
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.ThreadLocalRandom;
public class main extends JFrame {
JLabel text = new JLabel("Please choose a number between 1 & 10 ");
JLabel textVersuch = new JLabel();
JButton button = new JButton("Try");
int myNumber = ThreadLocalRandom.current().nextInt(1,10+1);
JTextField textField = new JTextField();
int count = 0;
//is there a better way to hide all this information, but still keep them useable for my methods?
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.openUI(); //error occurs
}
//How do I manage to start my method openUI() to start my game?
public void openUI(){
JFrame frame = new JFrame("Program");
frame.setSize(400,400);
frame.setLocation(800,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultLookAndFeelDecorated(true);
text.setBounds(0,50,400,25);
textVersuch.setBounds(300,0,100,25);
textField.setBounds(0,150,50,25);
button.setBounds(50,150,100,25);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
String textFromTextfield = textField.getText();
int number = Integer.parseInt(textFromTextfield);
if(number<1 || number>10){
text.setText("Your number has to be between 1 & 10 ");
textField.setText("");
}else{
guess(number);
}
}catch (Exception error){
text.setText("Please enter a digit! ");
textField.setText("");
}
}});
frame.add(button);
frame.add(textField);
frame.add(text);
frame.add(textVersuch);
frame.setLayout(null);
frame.setVisible(true);
}
public void close(JFrame frame){
frame.dispose(); //here I want to close the game
}
public void guess(int number ) throws InterruptedException {
count++;
textVersuch.setText(count + " tries!");
if(number == myNumber){
text.setText("You was right! " + " You tried " + count + " time(s) :)" );
button.setText("Restart");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//How can I restart my JFrame?
}
});
} else if (count < 3) {
text.setText("Wrong guess! Retry");
if (number < myNumber){
text.setText("Your searched number is bigger than" + number );
}else {
text.setText("Your searched number is lower than" + number );
}
} else {
text.setText("Sorry, you lost the number was " + myNumber);
}
textField.setText("");
}
}
I've a custom Entry Renderer in Android and I've implemented BeforeTextChanged event so that I get the text which is gonna be entered, but it doesn't return that text.
I've implemented in two different ways:
First implementing ITextWatcher by the class and then overriding the mentioned event (helping this link):
void ITextWatcher.BeforeTextChanged(ICharSequence s, int start, int count, int after)
{
var test1 = new string(s?.ToArray());
var test2 = Control?.Text;
SpannableString spannableString = new SpannableString(s);
BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.Blue);
spannableString.SetSpan(backgroundSpan, start, start + count,
SpanTypes.ExclusiveExclusive);
var test3 = spannableString;
}
Second way:
Control.BeforeTextChanged += (sender, args) =>
{
var test1 = new string(args?.Text.ToArray());
var entry = sender as EditText;
var test2 = entry?.Text;
var test3 = Control?.Text;
};
But none of them will return the text that is about to be entered.
What I want is to access that text and only in some circumstances allowing it to be inserted.
I don't wanna use Behavior as it doesn't suit my need.
First way, ITextWatcher:
class MyEntryRenderer : EntryRenderer
{
public MyEntryRenderer() : base()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.SetBackgroundColor(global::Android.Graphics.Color.LightGreen);
Control.AddTextChangedListener(new MyTextWatcher());
}
}
}
class MyTextWatcher :Java.Lang.Object, ITextWatcher
{
public void AfterTextChanged(IEditable s)
{
Android.Util.Log.Error("lv", "afterTextChanged ---->" + s);
}
public void BeforeTextChanged(ICharSequence s, int start, int count, int after)
{
Android.Util.Log.Error("lv", "beforeTextChanged ----> s=" + s + "----start=" + start
+ "----after=" + after + "----count" + count);
}
public void OnTextChanged(ICharSequence s, int start, int before, int count)
{
Android.Util.Log.Error("lv", "onTextChanged ---->s=" + s + "----start=" + start
+ "----before=" + before + "----count" + count);
}
}
it works well.
Second way, Control.BeforeTextChanged, it also works well.
it doesn't return that text
The methods you provided in your question, they are all work well in my phone. Please show more codes, so I can help you find where is wrong.
I am trying to find the text position in PDF page?
What I have tried is to get the text in the PDF page by PDF Text Extractor using simple text extraction strategy. I am looping each word to check if my word exists. split the words using:
var Words = pdftextextractor.Split(new char[] { ' ', '\n' });
What I wasn't able to do is to find the text position. The problem is I wasn't able to find the location of the text. All I need to find is the y co-ordinates of the word in the PDF file.
I was able to manipulate it with my previous version for Itext5. I don't know if you are looking for C# but that is what the below code is written in.
using iText.Kernel.Geom;
using iText.Kernel.Pdf.Canvas.Parser;
using iText.Kernel.Pdf.Canvas.Parser.Data;
using iText.Kernel.Pdf.Canvas.Parser.Listener;
using iTextSharp.text.pdf.parser;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class TextLocationStrategy : LocationTextExtractionStrategy
{
private List<textChunk> objectResult = new List<textChunk>();
public override void EventOccurred(IEventData data, EventType type)
{
if (!type.Equals(EventType.RENDER_TEXT))
return;
TextRenderInfo renderInfo = (TextRenderInfo)data;
string curFont = renderInfo.GetFont().GetFontProgram().ToString();
float curFontSize = renderInfo.GetFontSize();
IList<TextRenderInfo> text = renderInfo.GetCharacterRenderInfos();
foreach (TextRenderInfo t in text)
{
string letter = t.GetText();
Vector letterStart = t.GetBaseline().GetStartPoint();
Vector letterEnd = t.GetAscentLine().GetEndPoint();
Rectangle letterRect = new Rectangle(letterStart.Get(0), letterStart.Get(1), letterEnd.Get(0) - letterStart.Get(0), letterEnd.Get(1) - letterStart.Get(1));
if (letter != " " && !letter.Contains(' '))
{
textChunk chunk = new textChunk();
chunk.text = letter;
chunk.rect = letterRect;
chunk.fontFamily = curFont;
chunk.fontSize = curFontSize;
chunk.spaceWidth = t.GetSingleSpaceWidth() / 2f;
objectResult.Add(chunk);
}
}
}
}
public class textChunk
{
public string text { get; set; }
public Rectangle rect { get; set; }
public string fontFamily { get; set; }
public int fontSize { get; set; }
public float spaceWidth { get; set; }
}
I also get down to each individual character because it works better for my process. You can manipulate the names, and of course the objects, but I created the textchunk to hold what I wanted, rather than have a bunch of renderInfo objects.
You can implement this by adding a few lines to grab the data from your pdf.
PdfDocument reader = new PdfDocument(new PdfReader(filepath));
FilteredEventListener listener = new FilteredEventListener();
var strat = listener.AttachEventListener(new TextExtractionStrat());
PdfCanvasProcessor processor = new PdfCanvasProcessor(listener);
processor.ProcessPageContent(reader.GetPage(1));
Once you are this far, you can pull the objectResult from the strat by making it public or creating a method within your class to grab the objectResult and do something with it.
#Joris' answer explains how to implement a completely new extraction strategy / event listener for the task. Alternatively one can try and tweak an existing text extraction strategy to do what you required.
This answer demonstrates how to tweak the existing LocationTextExtractionStrategy to return both the text and its characters' respective y coordinates.
Beware, this is but a proof-of-concept which in particular assumes text to be written horizontally, i.e. using an effective transformation matrix (ctm and text matrix combined) with b and c equal to 0.
Furthermore the character and coordinate retrieval methods of TextPlusY are not at all optimized and might take long to execute.
As the OP did not express a language preference, here a solution for iText7 for Java:
TextPlusY
For the task at hand one needs to be able to retrieve character and y coordinates side by side. To make this easier I use a class representing both text its characters' respective y coordinates. It is derived from CharSequence, a generalization of String, which allows it to be used in many String related functions:
public class TextPlusY implements CharSequence
{
final List<String> texts = new ArrayList<>();
final List<Float> yCoords = new ArrayList<>();
//
// CharSequence implementation
//
#Override
public int length()
{
int length = 0;
for (String text : texts)
{
length += text.length();
}
return length;
}
#Override
public char charAt(int index)
{
for (String text : texts)
{
if (index < text.length())
{
return text.charAt(index);
}
index -= text.length();
}
throw new IndexOutOfBoundsException();
}
#Override
public CharSequence subSequence(int start, int end)
{
TextPlusY result = new TextPlusY();
int length = end - start;
for (int i = 0; i < yCoords.size(); i++)
{
String text = texts.get(i);
if (start < text.length())
{
float yCoord = yCoords.get(i);
if (start > 0)
{
text = text.substring(start);
start = 0;
}
if (length > text.length())
{
result.add(text, yCoord);
}
else
{
result.add(text.substring(0, length), yCoord);
break;
}
}
else
{
start -= text.length();
}
}
return result;
}
//
// Object overrides
//
#Override
public String toString()
{
StringBuilder builder = new StringBuilder();
for (String text : texts)
{
builder.append(text);
}
return builder.toString();
}
//
// y coordinate support
//
public TextPlusY add(String text, float y)
{
if (text != null)
{
texts.add(text);
yCoords.add(y);
}
return this;
}
public float yCoordAt(int index)
{
for (int i = 0; i < yCoords.size(); i++)
{
String text = texts.get(i);
if (index < text.length())
{
return yCoords.get(i);
}
index -= text.length();
}
throw new IndexOutOfBoundsException();
}
}
(TextPlusY.java)
TextPlusYExtractionStrategy
Now we extend the LocationTextExtractionStrategy to extract a TextPlusY instead of a String. All we need for that is to generalize the method getResultantText.
Unfortunately the LocationTextExtractionStrategy has hidden some methods and members (private or package protected) which need to be accessed here; thus, some reflection magic is required. If your framework does not allow this, you'll have to copy the whole strategy and manipulate it accordingly.
public class TextPlusYExtractionStrategy extends LocationTextExtractionStrategy
{
static Field locationalResultField;
static Method sortWithMarksMethod;
static Method startsWithSpaceMethod;
static Method endsWithSpaceMethod;
static Method textChunkSameLineMethod;
static
{
try
{
locationalResultField = LocationTextExtractionStrategy.class.getDeclaredField("locationalResult");
locationalResultField.setAccessible(true);
sortWithMarksMethod = LocationTextExtractionStrategy.class.getDeclaredMethod("sortWithMarks", List.class);
sortWithMarksMethod.setAccessible(true);
startsWithSpaceMethod = LocationTextExtractionStrategy.class.getDeclaredMethod("startsWithSpace", String.class);
startsWithSpaceMethod.setAccessible(true);
endsWithSpaceMethod = LocationTextExtractionStrategy.class.getDeclaredMethod("endsWithSpace", String.class);
endsWithSpaceMethod.setAccessible(true);
textChunkSameLineMethod = TextChunk.class.getDeclaredMethod("sameLine", TextChunk.class);
textChunkSameLineMethod.setAccessible(true);
}
catch(NoSuchFieldException | NoSuchMethodException | SecurityException e)
{
// Reflection failed
}
}
//
// constructors
//
public TextPlusYExtractionStrategy()
{
super();
}
public TextPlusYExtractionStrategy(ITextChunkLocationStrategy strat)
{
super(strat);
}
#Override
public String getResultantText()
{
return getResultantTextPlusY().toString();
}
public TextPlusY getResultantTextPlusY()
{
try
{
List<TextChunk> textChunks = new ArrayList<>((List<TextChunk>)locationalResultField.get(this));
sortWithMarksMethod.invoke(this, textChunks);
TextPlusY textPlusY = new TextPlusY();
TextChunk lastChunk = null;
for (TextChunk chunk : textChunks)
{
float chunkY = chunk.getLocation().getStartLocation().get(Vector.I2);
if (lastChunk == null)
{
textPlusY.add(chunk.getText(), chunkY);
}
else if ((Boolean)textChunkSameLineMethod.invoke(chunk, lastChunk))
{
// we only insert a blank space if the trailing character of the previous string wasn't a space, and the leading character of the current string isn't a space
if (isChunkAtWordBoundary(chunk, lastChunk) &&
!(Boolean)startsWithSpaceMethod.invoke(this, chunk.getText()) &&
!(Boolean)endsWithSpaceMethod.invoke(this, lastChunk.getText()))
{
textPlusY.add(" ", chunkY);
}
textPlusY.add(chunk.getText(), chunkY);
}
else
{
textPlusY.add("\n", lastChunk.getLocation().getStartLocation().get(Vector.I2));
textPlusY.add(chunk.getText(), chunkY);
}
lastChunk = chunk;
}
return textPlusY;
}
catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e)
{
throw new RuntimeException("Reflection failed", e);
}
}
}
(TextPlusYExtractionStrategy.java)
Usage
Using these two classes you can extract text with coordinates and search therein like this:
try ( PdfReader reader = new PdfReader(YOUR_PDF);
PdfDocument document = new PdfDocument(reader) )
{
TextPlusYExtractionStrategy extractionStrategy = new TextPlusYExtractionStrategy();
PdfPage page = document.getFirstPage();
PdfCanvasProcessor parser = new PdfCanvasProcessor(extractionStrategy);
parser.processPageContent(page);
TextPlusY textPlusY = extractionStrategy.getResultantTextPlusY();
System.out.printf("\nText from test.pdf\n=====\n%s\n=====\n", textPlusY);
System.out.print("\nText with y from test.pdf\n=====\n");
int length = textPlusY.length();
float lastY = Float.MIN_NORMAL;
for (int i = 0; i < length; i++)
{
float y = textPlusY.yCoordAt(i);
if (y != lastY)
{
System.out.printf("\n(%4.1f) ", y);
lastY = y;
}
System.out.print(textPlusY.charAt(i));
}
System.out.print("\n=====\n");
System.out.print("\nMatches of 'est' with y from test.pdf\n=====\n");
Matcher matcher = Pattern.compile("est").matcher(textPlusY);
while (matcher.find())
{
System.out.printf("from character %s to %s at y position (%4.1f)\n", matcher.start(), matcher.end(), textPlusY.yCoordAt(matcher.start()));
}
System.out.print("\n=====\n");
}
(ExtractTextPlusY test method testExtractTextPlusYFromTest)
For my test document
the output of the test code above is
Text from test.pdf
=====
Ein Dokumen t mit einigen
T estdaten
T esttest T est test test
=====
Text with y from test.pdf
=====
(691,8) Ein Dokumen t mit einigen
(666,9) T estdaten
(642,0) T esttest T est test test
=====
Matches of 'est' with y from test.pdf
=====
from character 28 to 31 at y position (666,9)
from character 39 to 42 at y position (642,0)
from character 43 to 46 at y position (642,0)
from character 49 to 52 at y position (642,0)
from character 54 to 57 at y position (642,0)
from character 59 to 62 at y position (642,0)
=====
My locale uses the comma as decimal separator, you might see 666.9 instead of 666,9.
The extra spaces you see can be removed by fine-tuning the base LocationTextExtractionStrategy functionality further. But that is the focus of other questions...
First, SimpleTextExtractionStrategy is not exactly the 'smartest' strategy (as the name would suggest.
Second, if you want the position you're going to have to do a lot more work. TextExtractionStrategy assumes you are only interested in the text.
Possible implementation:
implement IEventListener
get notified for all events that render text, and store the corresponding TextRenderInfo object
once you're finished with the document, sort these objects based on their position in the page
loop over this list of TextRenderInfo objects, they offer both the text being rendered and the coordinates
how to:
implement ITextExtractionStrategy (or extend an existing
implementation)
use PdfTextExtractor.getTextFromPage(doc.getPage(pageNr), strategy), where strategy denotes the strategy you created in step 1
your strategy should be set up to keep track of locations for the text it processed
ITextExtractionStrategy has the following method in its interface:
#Override
public void eventOccurred(IEventData data, EventType type) {
// you can first check the type of the event
if (!type.equals(EventType.RENDER_TEXT))
return;
// now it is safe to cast
TextRenderInfo renderInfo = (TextRenderInfo) data;
}
Important to keep in mind is that rendering instructions in a pdf do not need to appear in order.
The text "Lorem Ipsum Dolor Sit Amet" could be rendered with instructions similar to:
render "Ipsum Do"
render "Lorem "
render "lor Sit Amet"
You will have to do some clever merging (depending on how far apart two TextRenderInfo objects are), and sorting (to get all the TextRenderInfo objects in the proper reading order.
Once that's done, it should be easy.
For anyone looking for a simple Rectangle object this worked for me. I made these two classes, and call the static method "GetTextCoordinates" with your page and desired text.
public class PdfTextLocator : LocationTextExtractionStrategy
{
public string TextToSearchFor { get; set; }
public List<TextChunk> ResultCoordinates { get; set; }
/// <summary>
/// Returns a rectangle with a given location of text on a page. Returns null if not found.
/// </summary>
/// <param name="page">Page to Search</param>
/// <param name="s">String to be found</param>
/// <returns></returns>
public static Rectangle GetTextCoordinates(PdfPage page, string s)
{
PdfTextLocator strat = new PdfTextLocator(s);
PdfTextExtractor.GetTextFromPage(page, strat);
foreach (TextChunk c in strat.ResultCoordinates)
{
if (c.Text == s)
return c.ResultCoordinates;
}
return null;
}
public PdfTextLocator(string textToSearchFor)
{
this.TextToSearchFor = textToSearchFor;
ResultCoordinates = new List<TextChunk>();
}
public override void EventOccurred(IEventData data, EventType type)
{
if (!type.Equals(EventType.RENDER_TEXT))
return;
TextRenderInfo renderInfo = (TextRenderInfo)data;
IList<TextRenderInfo> text = renderInfo.GetCharacterRenderInfos();
for (int i = 0; i < text.Count; i++)
{
if (text[i].GetText() == TextToSearchFor[0].ToString())
{
string word = "";
for (int j = i; j < i + TextToSearchFor.Length && j < text.Count; j++)
{
word = word + text[j].GetText();
}
float startX = text[i].GetBaseline().GetStartPoint().Get(0);
float startY = text[i].GetBaseline().GetStartPoint().Get(1);
ResultCoordinates.Add(new TextChunk(word, new Rectangle(startX, startY, text[i].GetAscentLine().GetEndPoint().Get(0) - startX, text[i].GetAscentLine().GetEndPoint().Get(0) - startY)));
}
}
}
}
public class TextChunk
{
public string Text { get; set; }
public Rectangle ResultCoordinates { get; set; }
public TextChunk(string s, Rectangle r)
{
Text = s;
ResultCoordinates = r;
}
}
I want to write an algorithm to sequentially press keys F1-F3. My form has these controls:
lblF1
textboxF1
lblF2
textboxF2
lblF3
textboxF3
btnStart
In textboxF1-textboxF3 the time in seconds is entered. This when the program is to press the hotkey. It is important that the program can't press two keys at once, for example F1 and F2. It may not press more than one key in a second. When I click on btnStart it calls Run().
This is how I tried to resolve this:
static int counterF1 = 9999;
static int counterF2 = 9999;
static int counterF3 = 9999;
public void Run()
{
counterF1 = 9999;
counterF2 = 9999;
counterF3 = 9999;
while (true)
{
Loop();
}
}
public void Loop()
{
bool used = false;
if (counterF1 >= (int)textboxF1.text)
{
counterF1 = PressKey(VK_F1);
used = true;
}
if (counterF2 >= (int)textboxF2.text)
{
counterF2 = PressKey(VK_F2);
used = true;
}
if (counterF3 >= (int)textboxF3.text)
{
counterF3 = PressKey(VK_F3);
used = true;
}
if (used == false)
{
IncrementCounters();
Delay(1000);
}
}
public double PressKey(uint key)
{
myPostMessageA(hWindow, WM_KEYDOWN, (uint)key, (uint)key);
IncrementCounters();
return 1; //return 1 because one second
}
public void IncrementCounters()
{
counterF1++;
counterF2++;
counterF3++;
}
But often it doesn't press any key (it is possible it is too late, but can't be an omission). Can you explain how to make an algorithm for this?
We will use a class KeyStroke that stores the necessary data for a special key:
public class KeyStroke
{
public int period { get; set; } // Period in which to hit key
public int next { get; set; } // ticks to the next hit of this key
public int VK { get; set; } //KeyCode
}
public List<KeyStroke> keys = new List<KeyStroke>();
An Initialize() method is needed to read the data from the text boxes and to init the simulation. We utilize a timer with the interval of one second to run the simulation. In my example, I don't read from textboxes, but use constant values. Add the input and error handling. If you use WPF, you can bind the KeyStroke objects to the textboxes.
void Init()
{
//Initialize keys with according periods from input
keys.Clear();
keys.Add(new KeyStroke() { VK = VK_F1, period = 1, next = 1 });
keys.Add(new KeyStroke() { VK = VK_F2, period = 10, next = 10 });
keys.Add(new KeyStroke() { VK = VK_F3, period = 5, next = 5 });
//sort keys by period (descending), in order to handle long period keys, too
keys.Sort((first, second) => second.period.CompareTo(first.period));
//Start the program
var t = new DispatcherTimer();
t.Interval = TimeSpan.FromSeconds(1);
t.Tick += new EventHandler(t_Tick);
t.Start();
}
The tick event is similar to yours:
void t_Tick(object sender, EventArgs e)
{
bool used = false;
foreach (var key in keys)
{
if (key.next <= 0 && !used)
{
PressKey(key.VK);
key.next = key.period;
used = true;
}
key.next--;
}
}
I've developed UI application in blackberry.
On Button Click event I want to display result of adding two number.
How to handle this event in java app of Blackberry?
Best option to consume click event in ButtonField is to use FieldChangeListener. Just implement FieldChangeListener interface and apply ButtonField.setChangeListener():
class MenuScreen extends MainScreen implements FieldChangeListener {
EditField mNumberAEditField;
EditField mNumberBEditField;
ButtonField mAddButtonField;
public MenuScreen() {
super(DEFAULT_CLOSE);
mNumberAEditField = new EditField("A:", "2", 10,
EditField.FILTER_INTEGER);
add(mNumberAEditField);
mNumberBEditField = new EditField("B:", "2", 10,
EditField.FILTER_INTEGER);
add(mNumberBEditField);
mAddButtonField = new ButtonField("A + B",
ButtonField.CONSUME_CLICK);
add(mAddButtonField);
mAddButtonField.setChangeListener(this);
}
public void fieldChanged(Field field, int context) {
if(field == mAddButtonField)
{
showAddResult();
}
}
private void showAddResult() {
String message = "";
String aStr = mNumberAEditField.getText();
String bStr = mNumberBEditField.getText();
if(aStr == "")
message = "Enter A value!";
else if(bStr == "")
message = "Enter B value!";
else
{
int res = Integer.parseInt(aStr)+Integer.parseInt(bStr);
message = aStr+" + "+bStr+" = "+String.valueOf(res);
}
Dialog.inform(message);
}
}
Other option with FieldChangeListener is to declare and implement it inline. than you will not have to check from which field event is coming:
mAddButtonField.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
showAddResult();
}
});
or..
add(new ButtonField("Click Me")) {
protected boolean navigationClick(int status, int time) {
showAddResult();
return true;
}
});