Manage the Phone Number inside the editText - android

I have doubt to manage the phone number in android. I want to looks like when user enter the number inside the EditText then formate entering looks like 999 999 9999 and after complete the entering thf format should be looks like (999) 999-9999. How can achieve this thing. I did my coding something but when user click on cross key of keyboad to back the text the it is not working perfect. Any help please!
Code:
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
String phone = edit_profilephone.getText().toString();
if(phone.length() == 3)
{
edit_profilephone.setText(phone + " ");
edit_profilephone.setSelection(4);
}
else if(phone.length() == 7)
{
edit_profilephone.setText(phone + " ");
edit_profilephone.setSelection(8);
}
else if (phone.length() == 12)
{
int maxLength = 14;
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(maxLength);
edit_profilephone.setFilters(fArray);
StringBuilder buileString = new StringBuilder();
String splitnumber[] = phone.split("\\s+");
for (int i=0; i<splitnumber.length; i++)
{
if (i == 0)
{
buileString.append("(" + splitnumber[i] + ")");
}
else if (i == 1)
{
buileString.append(" " + splitnumber[i]);
}
else
{
buileString.append("-" + splitnumber[i]);
}
}
edit_profilephone.setText(buileString.toString());
}
}

you can also go through with
EditText inputField = (EditText) findViewById(R.id.inputfield);
inputField.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
For more Idea...

You can use PhoneNumberUtils.formatNumber() methods.
Or you can use a PhoneNumberFormattingTextWatcher. I've never used this before, but it seems to do all the work you want to do.

Also don't forget to put the text type in XML document for the edit text, it might help:) Good luck! Like this:
EditText
android:id="#+id/editTextId"
android:inputType="phone"
android:digits="0123456789+"
/>

Related

How to change text color while typing special word

on MultpuAutocompletTexView while Typing I want to make some special word that is start with # want to make that word alone with some colour, how can I do this any help.
so when ever I type with # that word should be in colour text.
like this image
Use TextWatcher with Spanable text, and every time you need to check the last enter word, means the 0 index of last word is #, if YES then apply Spanable for EditText.
please have a look on below code.
define this variable on public level
int beforeChangeSize = 0, afterChangeSize = 0, cusrsorPos = 0, posOflastSpace = 0;
String lastcursorSubString = "";
#Override
public void afterTextChanged(Editable editable) {
if (afterChangeSize > beforeChangeSize) {
cusrsorPos = 0;
posOflastSpace = 0;
lastcursorSubString = "";
cusrsorPos = txt_search.getSelectionStart();
String sudString = txt_search.getText().toString().substring(0, cusrsorPos);
posOflastSpace = sudString.lastIndexOf(" ");
posOflastSpace = (posOflastSpace == -1) ? 0 : posOflastSpace;
lastcursorSubString = sudString.substring(posOflastSpace, cusrsorPos).trim();
if ((lastcursorSubString.length() > 1 &&(lastcursorSubString.charAt(0) == '#') {
textlable.setText(""+lastcursorSubString);
// txt_search.getText().replace(posOflastSpace+1, cusrsorPos, Html.fromHtml("<font color=#FE642E>" + lastcursorSubString + "</font>"));
// txt_search.showDropDown();
editable.setSpan(new ForegroundColorSpan(Color.RED),
posOflastSpace+1,
cusrsorPos,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
you should use combination of textWatcher and spannable text
use text watcher to see what user is typing and use spannable text to give special color or format to part of your text in textView or EditText
good tutorial for spannable text :
https://medium.com/google-developers/spantastic-text-styling-with-spans-17b0c16b4568
and documentation for text watcher here :
https://developer.android.com/reference/android/widget/TextView.html#addTextChangedListener(android.text.TextWatcher)
You can add your own TextChangedListener and implement onTextChanged method
myAutoTxtView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence text, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence text, int start, int before, int count) {
if (text.charAt(start) == '#') {
//change color
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
this code to change color - use it in on text change listener like above (its kotlin you need to modify it to Java if you want to)
//get text
val str = editText.text.toString()
//get last word
val splitStr = str.trim { it <= ' ' }.split("\\s+".toRegex()).dropLastWhile {
it.isEmpty() }.toTypedArray()
val ColorWord = splitStr.last()
//get the sentence without the last word
val textButLast = str.substring(0, str.lastIndexOf(" "))
//change the last word color
val LastWord = "<font color='#EE0000'>$ColorWord</font>"
//put the last word with the sentence again
editText.setText(Html.fromHtml(textButLast + LastWord))

Prevent whitespace in a string after one is entered

I made a code where user can't enter first space in a string.
User is allowed to enter white space after min 2 characters.
I need to redefine my method so user enters white space once, and only once after the two or more characters. After that it should be prevented. How do I do that?
case UPDATE_NAME:
if (firstName.getText().toString().startsWith(" "))
firstName.setText(firstName.getText().toString().trim());
if (firstName.getText().toString().contains(" "))
firstName.setText(firstName.getText().toString().replace(" ", " "));
int indexOfSpace = firstName.getText().toString().lastIndexOf(" ");
if (indexOfSpace > 0) {
String beforeSpace = firstName.getText().toString().substring(0, indexOfSpace);
String[] splitted = beforeSpace.split(" ");
if (splitted != null && splitted.length > 0) {
if (splitted[splitted.length - 1].length() < 2)
firstName.setText(firstName.getText().toString().trim());
}
}
Use a regex pattern. I made one that should match your requirements.
\S{2}\S*\s\S*\n
Explanation:
\S{2} two non whitespace
\S* n non whitespace
\s a whitespace
\S* n non whitespace
\n newline (i only added that for regexr, you may not need it)
Alternate way:
Iterate over String.charAt(int), return false if there is a whitespace in the first two chars, count all whitespaces, return false if n > 1.
This method should meet your requirements:
private static boolean isValidFirstName(String firstName) {
if (firstName != null && !firstName.startsWith(" ")) {
int numberOfSpaces = firstName.length() - firstName.replace(" ", "").length();
if (firstName.length() < 2 || numberOfSpaces <= 1) {
return true;
}
}
return false;
}
What you need to do is use a TextWatcher
public class CustomWatcher implements TextWatcher {
private String myText;
private int count = 0;
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after){
myText= s;
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
//check if there is a space in the first 2 characters, if so, sets the string to the previous before the space
if(s.length() < 3 && s.contains(" "))
s= myText;
//if the length is higher than 2, and the count is higher than 0 (1 space added already), puts the string back if a space is entered
else if(s.contains(" ") && count > 0)
s= myText;
//If none of the above is verified and you enter a space, increase count so the previous if statement can do its job
else if(s.contains(" "))
count++;
}
}
And then, set it to your EditText
mTargetEditText.addTextChangedListener(new CustomWatcher());
You can control your editText(I assume) with a TextWatcher, you would only need to check inside afterTextChanged() if length is <2 and else if the string contains the char " ".

How to type decimal values (money) from right to left?

Suppose when a field is loaded, its empty. When the user types 1, it says 0.01, then he types another 0 after the 1 (10) it becomes 0.10. When he types another 1, it becomes 1.10.
Just like entering the price of a product. How do I do that on Android? I'm quite stumped to be honest since I've never tried something like this. Is there some special input method for this?
Here's the code I wrote for myself:
private String addCurrencySign(String digits) {
String string = "£";
// Amount length greater than 2 means we need to add a decimal point
if (digits.length() > 2) {
String pound = digits.substring(0, digits.length() - 2); // Pound part
String pence = digits.substring(digits.length() - 2); // Pence part
string += pound + "." + pence;
} else if (digits.length() == 1) {
string += "0.0" + digits;
Log.d(TAG, "length 1 " + string);
} else if (digits.length() == 2) {
string += "0." + digits;
Log.d(TAG, "length 2 " + string);
}
return string;
}
This addCurrencySign method is triggered each time when user trying to type on the number pad. The number pad is consist of several digit buttons (just like POS handheld or calculator).
Since you don't need to build a keypad with buttons, could you try intercept the keyboard events, which is described in Handling Keyboard Actions and maybe write something like this:
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_0:
return true;
case KeyEvent.KEYCODE_1:
return true;
case KeyEvent.KEYCODE_2:
return true;
case KeyEvent.KEYCODE_3:
return true;
......
default:
return super.onKeyUp(keyCode, event);
}
}
Maybe you don't have to use switch clause, my idea is to intercept the key entering 0~9 digits and for each 0~9, call addCurrencySign method.
Use:
TextWatcher watcher = new TextWatcher(){
afterTextChanged(Editable s){}
beforeTextChanged(CharSequence s, int start, int count, int after){}
onTextChanged(CharSequence s, int start, int before, int count){}
}
yourEditText.addTextChangedListener(watcher);
Here you will find more info about TextWatcher http://developer.android.com/reference/android/text/TextWatcher.html
OK guys.. I have a temporary workaround. This can't be termed as the perfect solution but its a workaround that works well in my case.
I couldn't figure out a way to stop the stackoverflow error. My workaround? Make the EditText field take input, but display the currency output onto a TextView, and make the EditText disappear from the UI so the user can't see that he is typing just 1234 instead of 12.34.
Here is the code. The addCurrencySign function comes from #ss1271.
amountpaid.addTextChangedListener(new TextWatcher()
{
#Override public void onTextChanged(CharSequence s, int start, int before, int count)
{
amount.setText(addCurrencySign(s.toString()));
}
#Override public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override public void afterTextChanged(Editable s)
{
}
});
Here's the function that the user posted. It works very well.
private String addCurrencySign(String digits)
{
String string = "&"; // Your currency
// Amount length greater than 2 means we need to add a decimal point
if (digits.length() > 2)
{
String pound = digits.substring(0, digits.length() - 2); // Pound
// part
String pence = digits.substring(digits.length() - 2); // Pence part
string += pound + "." + pence;
}
else if (digits.length() == 1)
{
string += "0.0" + digits;
Log.d("TextWatcher", "length 1 " + string);
}
else if (digits.length() == 2)
{
string += "0." + digits;
Log.d("TextWatcher", "length 2 " + string);
}
return string;
}
Here's the 'invisible' edittext:
<EditText
android:id="#+id/amoundpaid"
android:layout_width="1dp"
android:layout_height="1dp"
android:background="#00000000"
android:ems="10"
android:inputType="number"
android:textColor="#00ffffff" >
<requestFocus />
Here's the field that will show the output text (with currency sign and proper decimal point value):
<TextView
android:id="#+id/amount"
android:layout_width="210dp"
android:layout_height="50dp"
android:background="#80000000"
android:gravity="center|center_vertical"
android:textColor="#ffffff"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />
I know this is not a optimum solution, but it works. I needed the functionality and this is what I had to do to get it. If someone can fix the stackoverflow error, please post and mods will change the answer to that one (once its verified).

Android: Autocomplete TextView Similar To The Facebook App

I have an AutoCompleteTextView in my app. The app makes use of the Facebook SDK. I followed the code from this question on SO: https://stackoverflow.com/a/12363961/450534 to the dot and have a functioning search (filtering) activity.
Now, how do I get an inline Autocomplete like the Facebook App after the # symbol is typed and still hold the other text typed by the user? The activity in question is for a Status Update and can contain the user's Friends along with other text. The AutoCompleteTextView or the EditText will naturally be a multi-line one. For a status update you see.
I know for the lack of any code in this post, I risk getting downvoted or perhaps even having the question closed. But it's really a standard boiler plate list filtering code.
EDIT: The FriendCaster app for Android also does the same.
First make your EditText into a MultiAutoCompleteTextView. A MultiAutoCompleteTextView allows you to replace certain parts of the text, for example text after '#'.
The you can do something like this:
final MultiAutoCompleteTextView inputEditText = (MultiAutoCompleteTextView) dialog.findViewById(R.id.MyEditText);
String[] COUNTRIES = new String[] { "Belgium", "France", "Italy", "Germany", "Spain" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, COUNTRIES);
inputEditText.setAdapter(adapter);
inputEditText.setThreshold(1); //Set number of characters before the dropdown should be shown
//Create a new Tokenizer which will get text after '#' and terminate on ' '
inputEditText.setTokenizer(new Tokenizer() {
#Override
public CharSequence terminateToken(CharSequence text) {
int i = text.length();
while (i > 0 && text.charAt(i - 1) == ' ') {
i--;
}
if (i > 0 && text.charAt(i - 1) == ' ') {
return text;
} else {
if (text instanceof Spanned) {
SpannableString sp = new SpannableString(text + " ");
TextUtils.copySpansFrom((Spanned) text, 0, text.length(), Object.class, sp, 0);
return sp;
} else {
return text + " ";
}
}
}
#Override
public int findTokenStart(CharSequence text, int cursor) {
int i = cursor;
while (i > 0 && text.charAt(i - 1) != '#') {
i--;
}
//Check if token really started with #, else we don't have a valid token
if (i < 1 || text.charAt(i - 1) != '#') {
return cursor;
}
return i;
}
#Override
public int findTokenEnd(CharSequence text, int cursor) {
int i = cursor;
int len = text.length();
while (i < len) {
if (text.charAt(i) == ' ') {
return i;
} else {
i++;
}
}
return len;
}
});
One "problem" with this is that the popup will appear under the EditText view. To move it up and place it under the text that is currently written you can do something like this:
inputEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Layout layout = inputEditText.getLayout();
int pos = inputEditText.getSelectionStart();
int line = layout.getLineForOffset(pos);
int baseline = layout.getLineBaseline(line);
int bottom = inputEditText.getHeight();
inputEditText.setDropDownVerticalOffset(baseline - bottom);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
Note: This does not currently take care of the dropdown position in the case that there are more lines in the edittext than the edittext can show.
https://github.com/dhaval001/linkable_text_view.git
Simple way to create link text, such as #username or #hashtag, in Android TextView and EditText with multiautocomplete textview. link facebook and instagram
Features
Match single strings or regex pattern to set links
Change the color of the linked text
Set the style of the linked text: BOLD, ITALIC, or BOLD_ITALIC
Set the underlined of the linked text
Specify click actions of a specific word
OnTextChangedListener listener for LinkableEditText

Dialog shows alpha Characters?

Am using Custom Dialog to shows the list of number based on user input,in Edittext box. I added Textwatcher everything is wrking fine until user try to give input more fast its showing one more Dialog with Black stripes with some alpha characters How to rectify this one?
My Screenshot is 1
Custom Dialog code here
this is my code which am using in textwatcher
#Override
public void afterTextChanged(Editable s) {
String str = s.toString();
str_length = str.length();
Log.v("length_before", "" + count + "" + str_length);
if (str_length == count + 1) {
return;
}
if (str_length >= 3) {
return;
}
if (str_length > count) {
count = str.length();
AmountDialog.amount_dialog(TicketIssueActivity.this, str,
amount);
} else if (str_length < count) {
count = str_length - 1;
Log.v("length slese", "" + count + "" + str_length);
}
}
If all you want is number in amount field. you can set:
android:inputType="number"
in the EditText field of your layout xml file.
That's all I got from the question. Please post more details or code if this doesn't solve the problem.

Categories

Resources