I want to set animation on ImageView when user put more than 3 characters. I wrote a code to do this. Main problem is when I keep putting more than 3 characters the animation starts again from 0 position always when new character is added, so it doesn't looks good.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_user_first);
initViews();
imageButtonNext.setEnabled(false);
horizontalScrollView.post(() -> horizontalScrollView.scrollTo(0, 0));
horizontalScrollView.setOnTouchListener((v, event) -> true);
editTextEnterName.addTextChangedListener(nameTextWatcher);
pulse = AnimationUtils.loadAnimation(NewUserFirst.this, R.anim.pulse);
imageButtonNext.setOnClickListener(view -> {
intent = new Intent(this, NewUserSecond.class);
startActivity(intent);
});
}
public void buttonAnimation(){
if(buttonBoolean){
imageButtonNext.setAnimation(pulse);
imageButtonNext.setColorFilter(ContextCompat.getColor(NewUserFirst.this, R.color.accent));
imageButtonNext.setEnabled(true);
} else {
imageButtonNext.clearAnimation();
imageButtonNext.setColorFilter(ContextCompat.getColor(NewUserFirst.this, R.color.gray));
imageButtonNext.setEnabled(false);
}
}
private final TextWatcher nameTextWatcher = 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) {
nameInput = editTextEnterName.getText().toString().trim();
if (nameInput.length() >= 3) {
buttonBoolean = true;
} else {
buttonBoolean = false;
}
}
#Override
public void afterTextChanged(Editable editable) {
buttonAnimation();
}
};
So the question is, what changes I need to make in my code to set animation, and do not renew it every time when add next character.
Here is the answer:
public void buttonAnimation(){
if(buttonBoolean){
if (!imageButtonNext.isEnabled()) {
imageButtonNext.setAnimation(pulse);
imageButtonNext.setColorFilter(ContextCompat.getColor(this, R.color.accent));
imageButtonNext.setEnabled(true);
}
} else {
imageButtonNext.clearAnimation();
imageButtonNext.setColorFilter(ContextCompat.getColor(this, R.color.gray));
imageButtonNext.setEnabled(false);
}
}
We need to add if statement in animation method. Program check animation is currently enabled, when yes, program do nothing. Result is animation triggered once live his own life until we modify edittext to length less than 3.
Related
I was creating user interface where user have to enter the mobile number in EditText. maxLength of that EditText is 10. Now I want when 10 digits entered by the user the keyboard automatically get hide. How to implement this. I already searched on google but not a single code worked for me. Below is my XML & Fragment code.
XML Code
<EditText
android:id="#+id/editTextPhone"
style="#style/EditText"
android:background="#drawable/border_design"
android:inputType="phone"
android:hint="#string/editText_phone_hint"
android:maxLength="10"
android:drawableLeft="#drawable/phone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Fragment Code
public class MobileNumberFragment extends Fragment {
String mobileNumber;
editTextNumber = (EditText) view.findViewById(R.id.editTextPhone);
protected boolean isValidNumber(String registerMobileNumber) {
if (registerMobileNumber != null && registerMobileNumber.length() == 10) {
return true;
}
return false;
}
private void SendOtp() {
mobileNumber = editTextNumber.getText().toString().trim();
if (!isValidNumber(mobileNumber)) //Condition so that no edit-text will remain empty
{
editTextNumber.setError("Enter the Valid Mobile Number");
editTextNumber.requestFocus();
return;
} else {
buttonSendOtp.setText("Processing...");
}
}
You can force Android to hide the virtual keyboard using the InputMethodManager, calling hideSoftInputFromWindow, passing in the token of the window containing your focused view.
// Check if no view has focus:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtName = (EditText)findViewById(R.id.txtName);
txtName.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) {
}
#Override
public void afterTextChanged(Editable s) {
if(s.toString().length() == 10){
HideKeyboardFormUser();
}
}
});
}
public void HideKeyboardFormUser(){
View view = getCurrentFocus();
InputMethodManager hideKeyboard = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
hideKeyboard.hideSoftInputFromWindow( view.getWindowToken(), 0);
}
}
This will force the keyboard to be hidden in all situations. In some cases you will want to pass in InputMethodManager.HIDE_IMPLICIT_ONLY as the second parameter to ensure you only hide the keyboard when the user didn't explicitly force it to appear (by holding down menu).
editTextNumber.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) {
}
#Override
public void afterTextChanged(Editable s) {
if (s.toString().length() >= 10) {
editTextNumber.setVisibility(View.GONE);
} else {
editTextNumber.setVisibility(View.VISIBLE);
}
}
});
You need to add a TextWatcher listener to the EditText, and hide the keyboard once the length reached 10.
editTextNumber = (EditText) view.findViewById(R.id.editTextPhone);
editTextNumber.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 (s.length() == 10){
hideSoftKeyboard(requireActivity());
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
public void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
View currentFocus = activity.getCurrentFocus();
if (inputMethodManager != null) {
IBinder windowToken = activity.getWindow().getDecorView().getRootView().getWindowToken();
inputMethodManager.hideSoftInputFromWindow(windowToken, 0);
inputMethodManager.hideSoftInputFromWindow(windowToken, InputMethodManager.HIDE_NOT_ALWAYS);
if (currentFocus != null) {
inputMethodManager.hideSoftInputFromWindow(currentFocus.getWindowToken(), 0);
}
}
}
I am trying to disable my button if my input edit texts are empty. I am using text watcher for this. To test it out , i have only tried with only two edit texts to start.
However, my button stays enabled no matter what.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_profile);
fnameInput = findViewById(R.id.et_firstname);
lnameInput = findViewById(R.id.et_lastname);
numberInput = findViewById(R.id.et_phone);
emailInput = findViewById(R.id.et_email);
nextBtn = findViewById(R.id.btn_next);
fnameInput.addTextChangedListener(loginTextWatcher);
lnameInput.addTextChangedListener(loginTextWatcher);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchNextActivity();
}
});
}
Text watcher method
private TextWatcher loginTextWatcher = 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 firstNameInput =firstNameInput.getText().toString().trim();
String lastNameInput = lastNameInput.getText().toString().trim();
// tried doing it this way
nextBtn.setEnabled(!firstNameInput.isEmpty() && !lastNameInput.isEmpty());
//What i've also tried
if(firstNameInput.length()> 0 &&
lastNameInput.length()>0){
nextBtn.setEnabled(true);
} else{
nextBtn.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
I expect the button to be disabled if one or all inputs are empty and enabled when all input fields are filled out.
create a method check all condition there like
private void checkTheConditions(){
if(condition1 && condition2)
nextBtn.setEnabled(true)
else
nextBtn.setEnabled(false)
}
call this method from afterTextChanged(Editable s) method
Let us consider this case for 2 EditTexts only as for now.
define 2 global CharSequence as below
CharSequence fName="";
CharSequence lName="";
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_profile);
fnameInput = findViewById(R.id.et_firstname);
lnameInput = findViewById(R.id.et_lastname);
numberInput = findViewById(R.id.et_phone);
emailInput = findViewById(R.id.et_email);
nextBtn = findViewById(R.id.btn_next);
fnameInput.addTextChangedListener(textWatcher);
lnameInput.addTextChangedListener(textWatcher2);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchNextActivity();
}
});
}
then you have to define different textwatcher for each of your Edittext
then inside each of these textWatcher assign values to CharSequence defined above
private TextWatcher textWatcher = 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) {
fName=s;
validate(); //method to enable or disable button (find method below)
}
#Override
public void afterTextChanged(Editable s) {
}
};
now textWatcher2
private TextWatcher textWatcher2 = 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) {
lName=s;
validate(); //method to enable or disable button (find method below)
}
#Override
public void afterTextChanged(Editable s) {
}
};
now write validate method
void validate(){
if (fName.length()>0 && lName.length()>0){
nextBtn.setEnabled(true);
}else {
nextBtn.setEnabled(false);
}
}
Oh! You did a small mistake. Use OR condition instead of AND. So your code should be
nextBtn.setEnabled(!firstNameInput.isEmpty() || !lastNameInput.isEmpty());
And TextWatcher will only notify when you will manually change the inputs of EditText. So TextWatcher will not wark at starting. So at first in onCreate method you should manually check those EditText feilds.
Edit:
Android new DataBinding library is best suitable for this purpose.
After I type, it gives me the message: your app isn`t responding.
do you want to close it?
WAIT OK
I think because of the edt_search.gettext().tostring() inside the setData()
private void setupViews() {
edt_search = findViewById(R.id.edt_search);
progress = findViewById(R.id.progress);
progress.hide();
edt_search.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) {
}
#Override
public void afterTextChanged(Editable editable) {
if (editable.length() != 0) {
setData();
}
}
});
}
private void setData() {
AndroidNetworking.post("uri")
.addBodyParameter("word", edt_search.getText().toString())
.build()
.getAsObjectList(Search.class, new ParsedRequestListener<List<Search>>() {
#Override
public void onResponse(List<Search> searches) {
for (Search search : searches) {
searchList.add(search);
adapter.notifyDataSetChanged();
}
loading(false);
}
#Override
public void onError(ANError anError) {
Log.e("android-networking", "error: " + anError.getLocalizedMessage());
}
});
}
You are probably guessing it right. By empiric experience, I found out it's problematic to call methods from EditText inside afterTextChanged method (at least without removing the text watcher first). If possible, it's much better to use the Editable object that is passed as an argument. So, in your case, you could try two approaches:
First (easiest and which I most recommend in this specific case): Pass your string to the method setData(), so you don't need to access your EditText in this method:
....
#Override
public void afterTextChanged(Editable editable) {
if (editable.length() != 0) {
setData(editable.toString());
}
}
....
private void setData(String searchString) {
AndroidNetworking.post("http://akhbaresteghlal.ir/search/getInformations.php")
.addBodyParameter("word", searchString)
.build()
....
Second option (if, by any reason, you absolutely need to access your editText directly): Remove the TextWatcher before calling setData() (and any method from EditText) and then add it again after.
....
#Override
public void afterTextChanged(Editable editable) {
if (editable.length() != 0) {
edt_search.removeTextChangedListener(this);
setData();
edt_search.addTextChangedListener(this);
}
}
....
private void setData() {
AndroidNetworking.post("http://akhbaresteghlal.ir/search/getInformations.php")
.addBodyParameter("word", edt_search.getText().toString())
.build()
....
Hope it helps!
I am using an EditText field in my application.
EditText is for entering the ddns input:
e.g www.example.com/xxxx
I want to restrict the length of the ddns id to 30 characters after "/" character.
i.e after "/" character, what follows must be of maximum 30 characters
I want to do it dynamically and restrict user to not type more than 30 characters.
How can i do it.
You can try the below way to restrict the user to enter less than 30 character.
tf.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//processing part
}
});
A very fast and ugly answer would look something like this:
yourEditText.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(s.toString().contains('/') {
if(s.toString().split('/')[1].length() == 30) {
//By only working with the EditText:
InputMethodManager imm = (InputMethodManager)
getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
yourEditText.setFocusable(false);
yoruEditText.setEnabled(false);
}
}
}
#Override
public void afterTextChanged(Editable s) {
}});
//What i think is the best implementation, adding a TextView sitting on top of
//EditText with visibility set to GONE
yourEditText.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(s.toString().contains('/') {
if(s.toString().split('/')[1].length() == 30) {
//By working with EditText and a TextView
yourEditText.setVisibility(View.GONE);
yourTextView.setVisibility(View.VISIBLE);
yourTextView.setText(s);
}
}
}
#Override
public void afterTextChanged(Editable s) {
}});
In any case you want to add a textWatcher to your editText and change it accordingly.
I'm writing a simple app in Android.
I've encountered this problem: I've two EditText and a Button. The value of one EditText must be a multiple of the other one EditText.
When the user insert a value in the first EditText and then press the button, the other EditText should show the value calculated with the user input.
This should be possible in other verse, too.
Like a simple unit converter. When I insert value1 in EditText1 and press convert the app must show the converted value in EditText2, but if I insert a value2 in EditText2 and press convert button the app must show the converted value in EditText1.
My problem is: how can I recognize in which EditText there are last user-input?
public void convert(View view) {
EditText textInEuro = (EditText) findViewById(R.id.euroNumber);
EditText textInDollar = (EditText) findViewById(R.id.dollarNumber);
if (toDollar) {
String valueInEuro = textInEuro.getText().toString();
float numberInEuro = Float.parseFloat(valueInEuro);
// Here the conversione between the two currents
float convertedToDollar = unit * numberInEuro;
// set the relative value in dollars
textInDollar.setText(Float.toString(convertedToDollar));
}
if (toEuro) {
String valueInDollar = textInDollar.getText().toString();
float numberInDollar = Float.parseFloat(valueInDollar);
//Here the conversione between the two currents
float convertedToEuro = numberInDollar / unit;
//set the relative value in dollars
textInEuro.setText(Float.toString(convertedToEuro));
}
}
This is the code written. I've thinked to use OnClickListener..but it isn't a good idea..
You can add a TextWatcher to your two EditText in order to know which one has been updated last.
public class MainActivity extends Activity {
EditText dollar;
EditText euro;
private static final int EURO = 0;
private static final int DOLLAR = 1;
private int lastUpdated = DOLLAR;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dollar = findViewById(R.id.dollar);
euro = findViewById(R.id.euro);
dollar.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
lastUpdated = DOLLAR;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
euro.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
lastUpdated = EURO;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void convert(View view) {
switch (lastUpdated) {
case EURO:
//Do work for euro to dollar
break;
case DOLLAR:
//Do work for dollar to euro
break;
default:
break;
}
}
}
I have a different way in mind,you can try this to achieve what you want:
when user comes first on activity,let him edit any edit text fields.(one is being filled,the other will be disabled until he pressed button)
let him click button
once the results are filled and he wants to edit one of the edittext,other edittext would be automatically empty
lets say you have editText_1 and editText_2,and your button is button_1.Also take a boolean variable called convertBoolean and make it false as default.
Now,
editText_1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(convertBoolean==false){
editText_2.setEnabled(false); //disable other edittext when one is being edited
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
#Override
public void afterTextChanged(Editable s) {
String s1=editText_1.getText().toString().trim();
String s2=editText_2.getText().toString().trim();
if(!s1.equals("") && !s2.equals("") && convertBoolean==true){
//of both are filled, empty second edittext
editText_2.setText("");
convertBoolean=false;
}
if(editText_1.getText().toString().trim().equals("") && convertBoolean==false){
editText_2.setEnabled(true);
}
}
});
editText_2.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(convertBoolean==false){
editText_1.setEnabled(false); //disable other edittext when one is being edited
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
#Override
public void afterTextChanged(Editable s) {
String s1=editText_1.getText().toString().trim();
String s2=editText_2.getText().toString().trim();
if(!s1.equals("") && !s2.equals("") && convertBoolean==true){
//of both are filled, empty first edittext
editText_1.setText("");
convertBoolean=false;
}
if(editText_2.getText().toString().trim().equals("") && convertBoolean==false){
editText_1.setEnabled(true);
}
}
});
button_1.setOnClickListener(new OnClickListener(){
public void onClick(){
convertBoolean=true;
editText_1.setEnabled(true);
editText_2.setEnabled(true);
}
});