I want to add masking ..
like 00000-0000000-0
etusercnic.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) {
try {
String str = s.toString();
if (s.length() == 5 || s.length() == 13) {
str += "-";
etusercnic.setText(str);
etusercnic.setSelection(str.length());
}
} catch (Exception ignored) {
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
It works perfectly,when first time i entered the value, but when i remove any digit it placed - sign. so what can i do..
I'm sure you're masking it for CNIC :D
Anyways here is my version of masking, it works perfectly:
etusercnic.setRawInputType(InputType.TYPE_CLASS_NUMBER);
etusercnic.addTextChangedListener(new TextWatcher() {
int len = 0;
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
String val = etusercnic.getText().toString();
if((val.length()==5 && len <val.length()) || (val.length()==13 && len<val.length())){
etusercnic.append("-");
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
String str = etusercnic.getText().toString();
len = str.length();
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
The xml of your Edittext should be something similar to this:
<EditText
android:id="#+id/nic_field"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/signup_cnic_hint"
android:singleLine="true"
android:inputType="date"
android:maxLength="15"
android:textColor="#000000"
android:textColorHint="#808080"
android:textSize="15sp"
/>
Good luck with your project! The easiest way I know to use a mask on EditText in your Android programs in Android Studio is to use MaskedEditText library (GitHub link).
It's a kind of custom EditText with Watcher that allows you to set a hint with different color (if you want if will be available even when user already started to type), mask and it's very easy to use :-)
It's very easy in your case:
compile 'ru.egslava:MaskedEditText:1.0.5'
<br.com.sapereaude.maskedEditText.MaskedEditText
android:id="#+id/phone_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone"
android:typeface="monospace"
mask:allowed_chars="1234567890"
mask:mask="#####-#######-#"
android:hint="0000000000000"
app:keep_hint="true"
/>
And that is! Good luck!
After some help.. i found a way. Correct Answer...Perfect Working. :)
etusercnic.addTextChangedListener(new TextWatcher() {
int len = 0;
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
String str = etusercnic.getText().toString();
len = str.length();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
String str = s.toString();
String val = etusercnic.getText().toString();
if ((val.length() == 5 && len < val.length()) || (val.length() == 13 && len < val.length())) {
str += "-";
etusercnic.setText(str);
etusercnic.setSelection(str.length());
}
} catch (Exception ignored) {
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
Related
I have to create a comma-separated array. So after 10 comma edittext should not accept the text or latter enter by user <- I have to do this. Here's the code I am using. but it goes to infinite loop after if condition in onTextChanged().
addTagsEt.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 (tagsArray != null && tagsArray.length == 10) {
Toast.makeText(CreateJobTwoActivity.this, "Only 10 tags considered", Toast.LENGTH_SHORT).show();
addTagsEt.setText(addTagsEt.getText().toString().substring(0, addTagsEt.getText().toString().length() - 1));
}
}
#Override
public void afterTextChanged(Editable s) {
if (addTagsEt.getText().toString().contains(",")) {
tagsArray = addTagsEt.getText().toString().split("\\s*,\\s*");
tagsArr.addAll(Arrays.asList(tagsArray));
}
}
});
Change onTextChanged function to:
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 0) {
String str = s.toString();
int l = str.length() - str.replaceAll(",","").length();
if (l >= 10){
Toast.makeText(CreateJobTwoActivity.this, "Only 10 tags considered", Toast.LENGTH_SHORT).show();
String t = str.substring(0,start) + str.substring(start+count);
addTagsEt.setText(t);
addTagsEt.setSelection(start,start);
}
}
}
I am building a proto social network and I give the possibility to my users to Tag another user with the # , I'm using an autocomplete textview to show the dialog with the users # searched but I need to know when a user typed "#" and the letters following in the editext . I found this answer and it's exaclty what I need BUT I dont want to only get one character. I want the whole word to make a search in my database . Example, user types "#Jordan" in the middle of his paste text . I need to get the "#" and the "#Jordan " . How can I do it ?
Here s an example of my code
private final 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) {
if (!TextUtils.isEmpty(s) && start < s.length()) {
if (!mentionAdapter.isEmpty()) {
mentionAdapter.clear();
}
String lastWord = s.toString().substring(s.toString().lastIndexOf(" ") + 1);
if (lastWord != null){
if (lastWord.length() != 0) {
switch (lastWord.charAt(0)) {
case '#':
if (getAdapter() != hashtagAdapter) {
setAdapter(hashtagAdapter);
}
break;
case '#':
if (getAdapter() != mentionAdapter) {
setAdapter(mentionAdapter);
}
break;
}
}
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
I am aiming you are working on android java so here is the answer to your question
EditText editText = (EditText)findViewById(R.id.editText);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
String capturedString = getText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
});
this function will work whenever you tab spacebar "#Jordan " you will get string after '#' and before ' ' means you will get "Jordan" as a string
public String getText(String s) {
String startChar = "#";
String endChar = " ";
String output = getStringBetweenTwoChars(s, startChar, endChar);
System.out.println(output);
}
here is getStringBetweenTwoChars function
public String getStringBetweenTwoChars(String input, String startChar, String endChar) {
try {
int start = input.indexOf(startChar);
if (start != -1) {
int end = input.indexOf(endChar, start + startChar.length());
if (end != -1) {
return input.substring(start + startChar.length(), end);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return input;
}
You can do that by following code, If you want to #java from the string
**Hello this is #java the best programming language **
edt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(final CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable editable) {
String str = editable.toString();
String seperator = "#";
int seoPos = str.indexOf(seperator);
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(str);
boolean found = matcher.find();
if (seoPos != -1 && !found){
Log.d("TextChanged0","current Char "+str.substring(seoPos-1+seperator.length()));
}
}
});
String last = s.toString().substring(s.toString().lastIndexOf(" ") + 1);
Here is my TextInputEditText inside TextInputLayout. The hint you can see is set on TextInputLayout.
The user must write 255 characters otherwise the post is not valid.
I want the digit 255 to decrease as the user types and when reached to 0, the hint should be blank.
Here is my code :
private int charactersLeft = 256; is declared outside onCreate method.
And this code is inside onCreate method :
final TextInputLayout postTextInputBase = findViewById(R.id.post_text_input_base);
final TextInputEditText postTextInput = findViewById(R.id.post_text_input);
postTextInput.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 (charactersLeft == 0) {
postTextInputBase.setHint(null);
} else {
postTextInputBase.setHint((charactersLeft - 1) + " characters left");
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
I also tried to set charactersLeft to characterLeft -= 1 but, the java won't allow me to do that.
Then, how do I do this ?
Use app:counterEnabled="true"
Whether the character counter functionality is enabled or not in this layout.
Also use app:counterMaxLength="250"
Sets the max length to display at the character counter.
Try this
<android.support.design.widget.TextInputLayout
android:id="#+id/post_text_input_base"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:counterEnabled="true"
app:counterMaxLength="250">
<EditText
android:id="#+id/post_text_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="UserName" />
</android.support.design.widget.TextInputLayout>
OUTPUT
EDIT
public class RecyclerViewActivity extends AppCompatActivity {
TextInputLayout postTextInputBase;
EditText postTextInputEditText;
int textLength = 9;
int len = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_view);
postTextInputBase = findViewById(R.id.post_text_input_base);
postTextInputEditText = findViewById(R.id.post_text_input);
postTextInputBase.setHint(textLength + " characters left");
postTextInputEditText.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) {
// first check your EditText is empty or not
if (!TextUtils.isEmpty(postTextInputEditText.getText().toString())) {
int len = postTextInputEditText.getText().toString().length();
// than check that editText text length is less than max length or not
// for test case i have set max length 10
if (len < 9) {
// if length of text is less than max length than use minus one from max length and set error in your text input layout
textLength--;
} else {
textLength++;
}
postTextInputBase.setHint(textLength + " characters left");
} else {
textLength = 9;
}
}
#Override
public void afterTextChanged(Editable s) {
if(postTextInputEditText.getText().toString().isEmpty()){
textLength = 9;
postTextInputBase.setHint(textLength + " characters left");
}
}
});
}
}
OUTPUT
EDIT 2 If you need set hint than use this
postTextInputBase.setHint(textLength + " characters left");
OUTPUT
NOTE Don't forgot to set android:maxLength="10" in edittext
Try this. Works with your existing code.
int charactersLeft = 256;
final TextInputLayout postTextInputBase = findViewById(R.id.post_text_input_base);
final TextInputEditText postTextInput = findViewById(R.id.post_text_input);
postTextInput.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.length() == 0) {
postTextInputBase.setHint(null);
}else {
postTextInputBase.setHint((charactersLeft - s.length()) + " characters left");
}
}
});
and Add android:maxLength="256" to your TextInputEditText
You may do it programatically using setOnKeyListener on the edit text.
TextInputLayout postTextInputBase = findViewById(R.id.post_text_input_base);
TextInputEditText postTextInput = findViewById(R.id.post_text_input);
postTextInput.setOnKeyListener((v, keyCode, event) -> {
// Do other things needed
postTextInputBase.setHint("Characters left: " + (256 - postTextInput.getText().length()));
return false;
});
To change Hint text only you can just change it on focus change.
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus)
editText.setHint("Enter name");
else
editText.setHint("Name");
}
});
I'm trying to color a word (house) as long as user types "house" in the edittext. This is what I've done:
if (textA.getText().toString().equals("house")){
String name = String.valueOf(textA.getText().toString().equals("house"));
name.setTextColor(Color.parseColor("#bdbdbd"));
}
my xml is as follows
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="15dp"
android:layout_marginEnd="15dp"
android:orientation="vertical"
android:padding="5dp">
<EditText
android:id="#+id/textA"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:inputType="textMultiLine"
android:maxLines ="4"
android:maxLength ="2000"
android:textColorHint="#color/grey"
android:background="#android:color/transparent"
android:gravity="top"/>
</LinearLayout>
however this causes the app to crash. Dont know what it is I'm doing wrong. I'm new to android. Any advice please?
this works for me
textA.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 str="home";
Spannable spannable =textA.getText();
if(s.length() != 0) {
textA.setTextColor(Color.parseColor("#0000FF"));
ForegroundColorSpan fcs = new ForegroundColorSpan( Color.GREEN);
String s1 = s.toString();
int in=0; // start searching from 0 index
// keeps on searching unless there is no more function string found
while ((in = s1.indexOf(str,in)) >= 0) {
spannable.setSpan(
fcs,
in,
in + str.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// update the index for next search with length
in += str.length();
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
You have to write code like below
textA.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 && s.contains("home")) name.setTextColor(Color.parseColor("#bdbdbd"));
});
equals return values is boolean.
so you have to change it.
public boolean equals(Object anObject)
if (textA.getText().toString().equals("house")){
textA.setTextColor(Color.parseColor("#bdbdbd"));
}
How to make make user input of 10 digit mobile number into 3-3-4 format?
example of 9848098480 into (984)-809-8480 in android??
Simply use the PhoneNumberFormattingTextWatcher, just call:
editText.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
Addition
To be clear, PhoneNumberFormattingTextWatcher's backbone is the PhoneNumberUtils class. The difference is the TextWatcher maintains the EditText while you must call PhoneNumberUtils.formatNumber() every time you change its contents.
OR
You can use this:
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="phone" />
Then try this code:
final EditText text = (EditText) findViewById(com.and.R.id.editText1);
text.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
boolean flag = true;
String eachBlock[] = text.getText().toString().split("-");
for (int i = 0; i < eachBlock.length; i++) {
if (eachBlock[i].length() > 4) {
flag = false;
}
}
if (flag) {
text.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL)
keyDel = 1;
return false;
}
});
if (keyDel == 0) {
if (((text.getText().length() + 1) % 5) == 0) {
if (text.getText().toString().split("-").length <= 3) {
text.setText(text.getText() + "-");
text.setSelection(text.getText().length());
}
}
a = text.getText().toString();
} else {
a = text.getText().toString();
keyDel = 0;
}
} else {
text.setText(a);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
}
});
use Himanshu Agarwal's method or just do:
String number = "1234567899";
System.out.println("(" + number.substring(0, 3) + ")-"
+ number.substring(3, 6) + "-" + number.substring(6));
ouput:
(123)-456-7899