Android disable text watcher when there are letters - java

I need help on my code.
I have an editText where the user enters the opening and closing time of the store and there is a checkbox with "Close".
The user enters the opening time 09:00 and then with the Text Watcher I add a space and a dash and the user enters the closing time 19:00, so that at the end the time is 09:00 - 19:00.
For example, if the store is closed on Saturday, the user must click on the checkbox and when the checkbox is clicked, the editText has the text set and it says "Closed".
The problem is that when I use the Text Watcher, if the length is equal to 6, it adds the hyphen and then when the user clicks on the checkbox instead of writing "Closed" it says "Closed-".
How can I remove that dash?
There is a condition where the Text Watcher turns off when there are only letters in the editText.
Does anyone have a solution to my problem, do you have any advice for me?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert__orari);
lunedi_inizio_uno = (EditText)findViewById(R.id.editText_uno_lunedi_inizio);
lunediUno = (CheckBox)findViewById(R.id.checkBox_uno_lunedi);
lunedi_inizio_uno.addTextChangedListener(new TextWatcher() {
int keyDell;
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
lunedi_inizio_uno.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL)
keyDell = 1;
int prevL = 0;
return false;
}
});
if (keyDell == 0) {
int len = lunedi_inizio_uno.getText().length();
if(len == 5) {
lunedi_inizio_uno.setText(lunedi_inizio_uno.getText() + " ");
lunedi_inizio_uno.setSelection(lunedi_inizio_uno.getText().length());
}if(len == 6) {
lunedi_inizio_uno.setText(lunedi_inizio_uno.getText() + "-");
lunedi_inizio_uno.setSelection(lunedi_inizio_uno.getText().length());
}if(len == 7) {
lunedi_inizio_uno.setText(lunedi_inizio_uno.getText() + " ");
lunedi_inizio_uno.setSelection(lunedi_inizio_uno.getText().length());
}
} else {
keyDell = 0;
}
}
#Override
public void afterTextChanged(Editable arg0) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
});
lunediUno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
lunedi_inizio_uno.setText("Chiuso");
}
}
});
}

I solved the problem, it was enough to add "-" in the length equal to 5 and eliminate the conditions of length equal to 6 and 7.

Related

How can I modify the input of multiple EditTexts at the same time, as I only modify one?

I have multiple EditTexts and I want to change the input of all of them at the same time, as I modify only one.(all of them take decimal numbers as input)
I stored the EditTexts in an array named 'editTexts'.
Here's what I tried
//Set the listener for each element
for (int i=0; i<editTexts.length; i++) {
final int finalI = i;
editTexts[i].addTextChangedListener(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) {
//if the editText which is currently edited is empty, set the input for all the rest to be '0.0'
if (editTexts[finalI].getText().toString().trim().length() == 0) {
for(EditText e : editTexts) {
if (e == editTexts[finalI])
continue;
e.setText("0.0");
}
} else {
float no = Float.parseFloat(s.toString() + "");
//Set the input of all the other editTexts to be the decimal number entered, multiplied by 2
for(EditText e : editTexts){
if(e == editTexts[finalI])
continue;
e.setText(no*2+"");
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
})
}
In this case the multiplication coefficient is just an example, it's not always gonna be 2. I used it just to test it out.
For some reason, when I change the input value, the app freezes.
Any help? Thanks!
Use LiveData to store your user input values.
Once it's value changes you can set value to each EditText. I think it is an easy way to implement.
Try it like this:
// et_x1, et_x2 and et_x3 are ids of EditTexts
//set inputType for all EditTexts as numberDecimal
EditText editText1 = findViewById(R.id.et_x1);
final EditText editText2 = findViewById(R.id.et_x2);
final EditText editText3 = findViewById(R.id.et_x3);
editText1.addTextChangedListener(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) {
String value = s.toString();
double x;
if (!value.equals("")) {
x = Double.parseDouble(value);
} else {
x = 0.0;
}
editText2.setText(Editable.Factory.getInstance().newEditable((String.valueOf(Math.pow(x, 2)))));
editText3.setText(
Editable.Factory.getInstance().newEditable((String.valueOf(Math.pow(x, 3)))));
}
#Override
public void afterTextChanged(Editable s) {
}
});
Hope it helps you!

creating a chat activity in android

After declaring and creating the textWatcher object, I would like to disable the send button and set it to gray if the chatText (edit text) is empty
I think it's a problem of ranking. Please help.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
list = (ListView)findViewById(R.id.listView);
list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
chatText = (EditText)findViewById(R.id.editText);
//chatText.setOnKeyListener(this);
me = true;
send = (Button)findViewById(R.id.button);
change = (Button)findViewById(R.id.button2);
list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
adp = new TheAdapter(getApplicationContext(),R.layout.chat);
list.setAdapter(adp);
chatText.addTextChangedListener(textWatcher);
checkFieldsForEmptyValues();
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
envoyer();
}
});
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
me = !me;
if (!me) {
change.setText(R.string.sender2);
} else {
change.setText(R.string.sender);
}
}
});
}
public void envoyer(){
adp.add(new messages(me, chatText.getText().toString()));
chatText.setText("");
}
private void checkFieldsForEmptyValues(){
String s1 = chatText.getText().toString();
if (s1.length() < 0 ) {
send.setEnabled(false);
} else {
send.setEnabled(true);
send.setBackgroundColor(Color.BLUE);
//send.setBackgroundColor((getResources().getColor(R.color.blue)));
}
}
In the onTextChanged is where you would check to see if the text field is empty:
chatText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 0) { //enable}
else if (s.length() == 0 { //disable }
In your code, you have if (s1.length() < 0 ) which I don't think will ever be true because the text size will never be less than 0.
// Disable on init
send.setEnabled(false);
// add text changer
chatText.addTextChangedListener(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) {
// Enable when input is != null and not empty. You can check string lenght too
send.setEnabled(s != null && !s.toString().isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
}
});
disable button before and add textwatch. You can also check if edittext value is not empty or verify string length.
I hope it will help you

How do I disable 2 buttons if a number field is empty

I have 2 buttons and 1 number field, if I press a button without something in the field, it crashes, so what I want to do is disable the buttons unless the number field has something in it, I have looked around for an answer but either they aren't relevant, or I'm not sure how it would fit into my code, here are the two onClick functions for each button. Thanks
public void toPounds(View view){
EditText amount = (EditText)findViewById(R.id.amount);
Double omrAmount = Double.parseDouble(amount.getText().toString());
Double gbrAmount = omrAmount * 1.79;
Toast.makeText(getApplicationContext(), "£" + gbrAmount.toString(), Toast.LENGTH_LONG).show();
}
public void toRiyals(View view){
EditText amount = (EditText)findViewById(R.id.amount);
Double gbrAmount = Double.parseDouble(amount.getText().toString());
Double omrAmount = gbrAmount / 1.79;
Toast.makeText(getApplicationContext(), omrAmount.toString() + " Riyals", Toast.LENGTH_LONG).show();
}
yourField.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if(s.length() == 0)
button1.setEnabled(false)
else
button1.setEnabled(true)
}
});
link
If you want to disable buttons if edit text is empty then you can do the following :
EditText amount = (EditText)findViewById(R.id.amount);
Button button = (Button) findViewById(R.id.button1);
if(amount.getText().toString().isEmpty()){
button.setEnabled(false);
}
amount.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if(s.length() == 0)
button1.setEnabled(false)
else
button1.setEnabled(true)
}
});
Not specifically an answer to your question, but generally speaking you would want to add some sort of check before you call your code which now crashes your application. It's not a good idea to to have code which crashes your app lingering around.
Maybe make a method like: isMyEditTextValid(...){..}

android - getting soft keyboard key presses

I am trying to get the key pressed on soft keyboard but am unable to do so.
Currently i am using the following code
#Override
public boolean dispatchKeyEvent(KeyEvent KEvent)
{
int keyaction = KEvent.getAction();
if(keyaction == KeyEvent.ACTION_DOWN)
{
int keycode = KEvent.getKeyCode();
int keyunicode = KEvent.getUnicodeChar(KEvent.getMetaState() );
char character = (char) keyunicode;
System.out.println("DEBUG MESSAGE KEY=" + character + " KEYCODE=" + keycode);
}
return super.dispatchKeyEvent(KEvent);
}
It is catching key events for the hardware keyboard but not for the virtual one. Can someone help me out
From the Android Official Page
Note: When handling keyboard events with the KeyEvent class and related APIs, you should expect that such keyboard events come only from a hardware keyboard. You should never rely on receiving key events for any key on a soft input method (an on-screen keyboard).
So you should use TextWatcher Interface to observe the characters pressed on the SoftKeyboard, example:
myEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
This should be your solution:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 1) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}

i want to validate multiple edittexts on click of device keypads done button

I have four edittext (atm pin kind of thing) and I want to validate all these four edittext on click of keypads done button(validations like - empty or wrong pin). so far, I could get the validations but it happens only if I click the done buttn twice. not able to figure out the issue, please help. I am a beginner. thanks!
Below is my code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.pin_new);
setTextFocus(edtpin1, edtpin2);
setTextFocus(edtpin2, edtpin3);
setTextFocus(edtpin3, edtpin4);
setTextFocus(edtpin5, edtpin6);
setTextFocus(edtpin6, edtpin7);
setTextFocus(edtpin7, edtpin8);
edtpin1.setOnEditorActionListener(new OnEditorActionListener(){
#Override
public boolean onEditorAction(TextView v, int arg1, KeyEvent arg2) {
switch (v.getId()) {
case R.id.btnBackPin:
Intent i = new Intent(getApplicationContext(),RegistrationProfileEmail.class);
startActivity(i);
break;
case R.id.btnCancelPin:
Intent in = new Intent(getApplicationContext(),Exit.class);
finish();
startActivity(in);
break;
case R.id.btnConfirmPin:
String s = new String();
s = edtpin1.getText().toString() + edtpin2.getText().toString()
+edtpin3.getText().toString() + edtpin4.getText().toString();
if ((edtpin5.getText().toString().trim().isEmpty())
|| (edtpin1.getText().toString().trim().isEmpty())
|| (edtpin2.getText().toString().trim().isEmpty())
|| (edtpin4.getText().toString().trim().isEmpty())
|| (edtpin3.getText().toString().trim().isEmpty())
|| (edtpin6.getText().toString().trim().isEmpty())
|| (edtpin7.getText().toString().trim().isEmpty())
|| (edtpin8.getText().toString().trim().isEmpty())) {
Toast.makeText(getApplicationContext(), "Enter the Pin",
Toast.LENGTH_SHORT).show();
edtpin1.setText(null);
edtpin2.setText(null);
edtpin3.setText(null);
edtpin4.setText(null);
edtpin5.setText(null);
edtpin6.setText(null);
edtpin7.setText(null);
edtpin8.setText(null);
edtpin1.requestFocus();
}
else if (edtpin1.getText().toString().trim().equalsIgnoreCase(edtpin5.getText().toString().trim())&& edtpin2.getText().toString().trim().equalsIgnoreCase(
edtpin6.getText().toString().trim()) && edtpin3.getText().toString().trim().equalsIgnoreCase( edtpin7.getText().toString().trim()) && edtpin4.getText().toString().trim().equalsIgnoreCase( edtpin8.getText().toString().trim()))
{
s = edtpin1.getText().toString() + edtpin2.getText().toString()
+ edtpin3.getText().toString()
+ edtpin4.getText().toString();
RegistrationPin.this.setPin(s);
}
// TODO move to payment option
else {
Toast.makeText(getApplicationContext(), "Pin is not matching",Toast.LENGTH_SHORT).show();
edtpin1.setText(null);
edtpin2.setText(null);
edtpin3.setText(null);
edtpin4.setText(null);
edtpin5.setText(null);
edtpin6.setText(null);
edtpin7.setText(null);
edtpin8.setText(null);
edtpin1.requestFocus();
}
break;
default:
break;
}
return false;
}
});
}
Create a class and implement the textwatcher like this:
private class CheckTextifEmpty implements TextWatcher {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (isEmptyCharacters(serverNumber)
|| isEmptyCharacters(textview1)
|| isEmptyCharacters(textview2)
|| isEmptyCharacters(textview3)) {
//do something here
} else {
//do something here
}
}
}
and add this method here:
private boolean isEmptyCharacters(TextView v) {
return v.getText().toString().trim().isEmpty();
}
and use it in your textview like this:
textview1.addTextChangedListener(new CheckTextIfEmpty());
You can use your validation like this without using a button
Refactor your code like this:
private boolean checkifValidate(TextView view1,View TextView2){
return view1.getText().toString().trim().contentEquals(view2.getText().toString());
}
Hope it helps,
edtpin1.setOnKeyListener(onSoftKeyboardDonePress);
private View.OnKeyListener onSoftKeyboardDonePress=new View.OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)
{
edtpin1.getText().toString();
edtpin2.getText().toString();
edtpin3.getText().toString();
edtpin4.getText().toString();
}
return false;
}
};

Categories