I wanted to make my hint to not animate if the edit text is empty. If user start typing the hint will move up, but if the edit text is empty, the hint will return into the edit text.
I have tried
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if(s.length() == 0){
textInputLayout4.setHintAnimationEnabled(false);
} else {
textInputLayout4.setHintAnimationEnabled(true);
}
}
but the hint does not act like how I wanted it to be.
Instead of beforeTextChanged(), try using afterTextChanged():
#Override
public void afterTextChanged(Editable s) {
if(s.toString().isEmpty()){
textInputLayout4.setHintAnimationEnabled(false);
} else {
textInputLayout4.setHintAnimationEnabled(true);
}
}
Related
I have three edittext values for which i am using textwatcher to update data.
I want that if i enter any value in anyone of the edit text then according to that value it should calculate and then update the edittext in which i entered the value automatically and after that set the value in other specif edit text and save the final value in string if need to send to any server.
//My Code
public class Land_details extends AppCompatActivity {
EditText land_acre_edit;
EditText land_kanal_edit;
EditText land_marla_edit;
Button land_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_land_details);
land_acre_edit = findViewById(R.id.land_acre_edit);
land_kanal_edit = findViewById(R.id.land_kanal_edit);
land_marla_edit = findViewById(R.id.land_marla_edit);
land_button = findViewById(R.id.save_land_detail);
land_acre_edit.addTextChangedListener(mytext_watcher);
land_marla_edit.addTextChangedListener(mytext_watcher);
land_kanal_edit.addTextChangedListener(mytext_watcher);
}
private TextWatcher mytext_watcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
String check_marla = land_marla_edit.getText().toString();
String check_kanal = land_kanal_edit.getText().toString();
String check_acre = land_acre_edit.getText().toString();
if (check_marla != null) {
if ((Integer.valueOf(check_marla) > 8)) {
check_acre =(String.valueOf(Integer.valueOf(check_kanal) + (Integer.valueOf(land_marla) / 20)));
check_marla=( String.valueOf(Integer.valueOf(land_marla) % 20));
check_acre = String.valueOf(check_acre) + (Integer.valueOf(check_kanal) / 8);
check_kanal = String.valueOf(Integer.valueOf(check_kanal) % 8);
land_marla_edit.setText(check_marla);
land_kanal_edit.setText(check_kanal);
land_acre_edit.setText(check_acre);
}}
}catch (NumberFormatException e){
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
I have tried to set my try catch code in aftertextChanged but at first it was giving me numberformatexception as soon as i enter a text above my contion my app crash but after that i tried using try catch to catch a numberformatexception after that i am able to add number above my condition and even after a long wait nothing happen can any one explain where i am going wrong.
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.
In my project, I am trying to change to different scenes depending on the number typed into an EditText. For example, it will launch as giving you 1 random number, and the EditText is default at 1, but if you want to have several random numbers at once, it will change scenes to go to a different layout.
I know to change scenes you use;
startActivity(new Intent(MainActivity.this, OtherActivity.class));
My trouble is with the if statement, if I use
if (value == 2);
It returns to me as "Cannot resolve symbol 'if(boolean)'"
Thank you for your time,
Lane
I think, by "Scenes" you mean to say you want to switch to a particular "activity" according to the number you type in the Edittext. If this is what you want to achieve, then you should add a text watcher to your edittext and monitor the value that is entered in the edittext onTextChange.
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.length() > 0) {
//do something like showing a toast or changing the activity
if (charSequence.toString().equalsIgnoreCase("1")) {
//do something
} else if (charSequence.toString().equalsIgnoreCase("2")) {
//do something
}
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
Remove semicolon ; from your if(value == 2); statement
It should be like:
if (value == 2) {
//do something here
}
Hey guys pretty new to android studio, like the title says I've tried to put the text within the EditText into a var called "username" which I want to be able to use within my inner class but I don't know how to make it accessible from within.
here's what I do with the EditText, within the onCreate: (KeyListener is the name of my inner class)
KeyListener KL_Instance = new KeyListener();
EditText input_text = (EditText) findViewById(R.id.inputText);
input_text.setOnKeyListener(KL_Instance);
String username = input_text.getText().toString();
And here's what i'm trying to do within the inner class:
public class KeyListener implements View.OnKeyListener
{
#Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent)
{
if (keyCode == KeyEvent.KEYCODE_AT)
{
Toast.makeText(MainActivity.this, "Do not type #", Toast.LENGTH_LONG).show();
}
//if the enter key is pressed, then check to see if username is 8 or more chars
if (keyCode == keyEvent.KEYCODE_ENTER)
{
//if it is, display it
if(username.length => 8)
{
Toast.makeText(MainActivity.this, "Hi, " + username, Toast.LENGTH_LONG).show();
}else //else, ask for a username of atleast 8 chars
{
Toast.makeText(MainActivity.this, "Please enter a username that is 8 or more chars", Toast.LENGTH_LONG).show();
}
}
return false;
}
}
But it says "cannot resolve symbol 'username'" and I cant access "input_text" within that class either so If someone could help me out here it would be greatly appreciated,
Thanks in advance :)
If you want store the value of the EditText you will need to update it with your listener and why use a KeyListener and why not just a TextWatcher like in this post here
EDIT :
You should do something like that
input_text.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged (Editable s){
username = s.toString();
}
#Override
public void beforeTextChanged (CharSequence s,int start,
int count, int after){
}
#Override
public void onTextChanged (CharSequence s,int start,
int before, int count){
}
});
TextWatcher is an implementation of the Design Pattern Observer so this code will be triger each time someone use the EditText, you have to deal with this by doing your logic in the TextWatcher like calling service or something else in charge of handle the username.
Trying to control the display of a message based on the value in a TextField. I have a fade away timed message display based on certain value input in the TextField box. Like to have a mouse hover over to display the same message while the input value is still invalid. Looks like the code I have below would still show the message even after the input value has beed changed to be valid.
...
errorLimit.textProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable,
String oldValue, String newValue) {
if (newValue.trim().length() > 0) {
int enteredValue = Integer.parseInt(newValue);
if (enteredValue <1 || enteredValue >25000) {
errorLimit.setStyle("-fx-text-fill: red");
Dialogs.flash(errorLimit, "The error limit can not be zero or blank or greater than 25,000");
if (errorLimit.getStyle().equals("-fx-text-fill: red")) {
errorLimit.setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent t) {
Dialogs.flash(errorLimit, "The error limit can not be zero or blank or greater than 25,000");
}
});
}
} else {
errorLimit.setStyle("-fx-text-fill: black");
}
}
}
});
...
Any idea how I can do this? Thanks!
Just put the if(...) clause inside the handle(...) method...
errorLimit.textProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable,
String oldValue, String newValue) {
if (newValue.trim().length() > 0) {
int enteredValue = Integer.parseInt(newValue);
if (enteredValue <1 || enteredValue >25000) {
errorLimit.setStyle("-fx-text-fill: red");
Dialogs.flash(errorLimit, "The error limit can not be zero or blank or greater than 25,000");
} else {
errorLimit.setStyle("-fx-text-fill: black");
}
}
}
});
errorLimit.setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent t) {
if (errorLimit.getStyle().equals("-fx-text-fill: red")) {
Dialogs.flash(errorLimit, "The error limit can not be zero or blank or greater than 25,000");
}
}
});
I would strongly suggest creating a BooleanProperty to indicate if the field is valid or not, instead of checking the value of the style; but that's a different issue I guess.