how to change the string display - android

how can i change string 980302 to string 98/03/02 in android studio
I have a variable of type string, for example 980302 I want to represent this way 98/03/02 in edittext Is
there a way?
Thanks for helping

This is probably the most trivial way of doing this...
String a = "980302";
String b = "" + a.charAt(0) + a.charAt(1) + "/" + a.charAt(2) + a.charAt(3) + "/" + a.charAt(4) + a.charAt(5);
YOUR_EDIT_TEXT.setText(b);
Or with a loop:
String a = "980302";
String b = "";
int i = 1;
while(i<a.length()){
if(i == 5){
b = b + a.charAt(i-1) + a.charAt(i);
}
else{
b = b + a.charAt(i-1) + a.charAt(i) + "/";
}
i = i + 2;
}
YOUR_EDIT_TEXT.setText(b);

If you're asking to show 980302 as 98/03/02 while typing, then the answer is using textchange event.
mMyEditText.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
String str = s.toString();
if(str.length()==2 || str.length()==5){
str+= '/';
//Set str in edittext
}
}
);

a = a.substring(0, 1) + "/" + a.substring(2, 3) + "/" + a.substring(4, 5);

Related

Android edit text decimal format

Can I ask how to format string value e.g. 5000000.00 to 5,000,000.00? Apparently I'm doing currency related stuff for android application, I can managed to just format string value 5000000 to 5,000,000 without the dot separator in the edit text. I would like to store the string value for later to be used to parseDouble so that I will need to calculate and have some decimals. I managed to do with just comma separator but any idea on how to make the dot to be shown in the edit text as well?
The following is my code:
amountText.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) {
amountText.removeTextChangedListener(this);
if(!amountText.getText().toString().equals(""))
{
try {
String editText = amountText.getText().toString();
String newStr = editText.replace("$", "").replace(",", "");
customer.getProperty().get(groupPosition).setAmount(newStr);
String formattedString = formatString(customer.getProperty().get(groupPosition).getAmount());
amountText.setText(formattedString);
amountText.setSelection(amountText.getText().length());
// to place the cursor at the end of text
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
amountText.addTextChangedListener(this);
}
});
public String formatString(String s)
{
String givenstring = s.toString();
Long longval;
if (givenstring.contains(",")) {
givenstring = givenstring.replaceAll(",", "");
}
longval = Long.parseLong(givenstring);
DecimalFormat formatter = new DecimalFormat("#,###,###");
String formattedString = formatter.format(longval);
return formattedString;
}
I have tested use parseDouble but when I input "." in EditText, it just won't appear, and if I used long variable instead, it will give wrong format and error. (java.lang.NumberFormatException: Invalid long: "500000.00"). All values are done in string and later processing I will just parse the value when doing calculation.
Thank you and appreciate for anyone guidance and I apologize if there exists the post that is similar as I did not manage to find solution yet.
This is working & fully tested code just copy & paste it to try
TextWatcher amountTextWatcher = 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) {
int cursorPosition = etAmount.getSelectionEnd();
String originalStr = etAmount.getText().toString();
//To restrict only two digits after decimal place
etAmount.setFilters(new InputFilter[]{new MoneyValueFilter(Integer.parseInt(2))});
try {
etAmount.removeTextChangedListener(this);
String value = etAmount.getText().toString();
if (value != null && !value.equals("")) {
if (value.startsWith(".")) {
etAmount.setText("0.");
}
if (value.startsWith("0") && !value.startsWith("0.")) {
etAmount.setText("");
}
String str = etAmount.getText().toString().replaceAll(",", "");
if (!value.equals(""))
etAmount.setText(getDecimalFormattedString(str));
int diff = etAmount.getText().toString().length() - originalStr.length();
etAmount.setSelection(cursorPosition + diff);
}
etAmount.addTextChangedListener(this);
} catch (Exception ex) {
ex.printStackTrace();
etAmount.addTextChangedListener(this);
}
}
}
};
etAmount.addTextChangedListener(amountTextWatcher);
Here is method to add comma seperator to decimal number
/**
* Get decimal formated string to include comma seperator to decimal number
*
* #param value
* #return
*/
public static String getDecimalFormattedString(String value) {
if (value != null && !value.equalsIgnoreCase("")) {
StringTokenizer lst = new StringTokenizer(value, ".");
String str1 = value;
String str2 = "";
if (lst.countTokens() > 1) {
str1 = lst.nextToken();
str2 = lst.nextToken();
}
String str3 = "";
int i = 0;
int j = -1 + str1.length();
if (str1.charAt(-1 + str1.length()) == '.') {
j--;
str3 = ".";
}
for (int k = j; ; k--) {
if (k < 0) {
if (str2.length() > 0)
str3 = str3 + "." + str2;
return str3;
}
if (i == 3) {
str3 = "," + str3;
i = 0;
}
str3 = str1.charAt(k) + str3;
i++;
}
}
return "";
}
Method to restrict only two digits after decimal place in edittext
/**
* Restrict digits after decimal point value as per currency
*/
class MoneyValueFilter extends DigitsKeyListener {
private int digits;
public MoneyValueFilter(int i) {
super(false, true);
digits = i;
}
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
CharSequence out = super.filter(source, start, end, dest, dstart, dend);
// if changed, replace the source
if (out != null) {
source = out;
start = 0;
end = out.length();
}
int len = end - start;
// if deleting, source is empty
// and deleting can't break anything
if (len == 0) {
return source;
}
int dlen = dest.length();
// Find the position of the decimal .
for (int i = 0; i < dstart; i++) {
if (dest.charAt(i) == '.') {
// being here means, that a number has
// been inserted after the dot
// check if the amount of digits is right
return getDecimalFormattedString((dlen - (i + 1) + len > digits) ? "" : String.valueOf(new SpannableStringBuilder(source, start, end)));
}
}
for (int i = start; i < end; ++i) {
if (source.charAt(i) == '.') {
// being here means, dot has been inserted
// check if the amount of digits is right
if ((dlen - dend) + (end - (i + 1)) > digits)
return "";
else
break; // return new SpannableStringBuilder(source,
// start, end);
}
}
// if the dot is after the inserted part,
// nothing can break
return getDecimalFormattedString(String.valueOf(new SpannableStringBuilder(source, start, end)));
}
}
Try this:
public void afterTextChanged(Editable view) {
String s = null;
try {
// The comma in the format specifier does the trick
s = String.format("%,d", Long.parseLong(view.toString()));
} catch (NumberFormatException e) {
}
// Set s back to the view after temporarily removing the text change listener
}
Source: How to Automatically add thousand separators as number is input in EditText

android check edit text field

Ok, how can I setup edit checks for a text field to limit enter to certain characters and length.
Below is something I worked on but if the cursor is in the first position and i hit return it crashed
final EditText editText1 = (EditText)findViewById(R.id.editText9);
editText1.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
editText1.setText("a");
editText1.setTag(1);
editText1.setId(idedittext1);
editText1.setBackgroundColor(0xff66ff66);
editText1.setPadding(20, 20, 20, 20);// in pixels (left, top, right, bottom)
//linear1.addView(editText1);
final String matchCharacters = "abcdefghijklmnopqrstuvwxyz.";
final CharSequence s_saved = "";
editText1.addTextChangedListener(new TextWatcher()
{
public void onTextChanged(CharSequence s, int start, int before, int count)
{
System.out.println("------------------------------------------------------------");
System.out.println("Entry: " + s + " " + s.length() + " " + start + " " + before + " " + count);
if (before == 1)
{
System.out.println("return");
}
if (s.length() > 4)
{
System.out.println("onTextChanged >4 replaced : " + s + " " + start + " " + before + " " + count);
String replaceStr = s.toString().substring(0, s.length() - 1);
editText1.setText(replaceStr);
editText1.setSelection(s.length() - 1);
}
if (s.length() > 0 && before != 1)
{
Integer sfound = 0;
String sstr = s.toString();
char[] sArray = sstr.toCharArray();
char[] mArray = matchCharacters.toCharArray();
System.out.println("sarray-marray " + " " + sstr + "-" + matchCharacters);
for (char sc : sArray) {
System.out.println("It worked1 " + sc);
for (char mc : mArray) {
System.out.println("It worked2 " + " " + sc + "-" + mc);
if (sc == mc) {
//System.out.println("It worked!");
sfound = sfound + 1;
} else {
//System.out.println("It did not work!");
}
}
}
System.out.println("slength-sfound " + " " + s.length() + "-" + sfound);
if (s.length() == sfound) {
System.out.println("MATCHED!");
} else {
System.out.println("NOMATCH!");
String replaceStr = s.toString().substring(0, s.length() - 1);
editText1.setText(replaceStr);
editText1.setSelection(s.length() - 1);
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Your can only enter the following characters: " + matchCharacters);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
}
Any help is appreciated.
Thanks
To limit the EditText length
<EditText
android:id="#+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="10"/>
To prevent certain character from being typed in
final EditText editText = (EditText) findViewById(R.id.edit_text);
final String matchCharacters = "aeiou";
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) {}
#Override
public void afterTextChanged(Editable editable) {
String text = String.valueOf(editText.getText());
boolean edited = false;
for(int i=0; i<matchCharacters.length(); i++){
char toPrevent = matchCharacters.charAt(i);
if(text.indexOf(toPrevent) < 0){
continue;
}
text = text.replace(String.valueOf(toPrevent), "");
edited = true;
}
if(edited){
editText.setText(text);
}
}
});

Math Quiz with true and false counters

I am implementing a scenario where user inputs an numeric answer in the edit text, which is being compared with addition of two numbers while inputting text using addTextChangeListener. I am trying to calculate true and false counters.
I get true counters perfectly in below code.
etTestAddAnswer.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 (etTestAddAnswer.getText().toString().length() == (String.valueOf((firstDigit + secondDigit)).length())) {
if (etTestAddAnswer.getText().toString().equalsIgnoreCase("")) {
etTestAddAnswer.setError("Left Blank");
YoYo.with(Techniques.Wobble)
.duration(750)
.playOn(tlTestAddAnswer);
} else {
if (Integer.parseInt(etTestAddAnswer.getText().toString()) == (firstDigit + secondDigit)) {
correctCounter += 1;
etTestAddAnswer.setText("");
Toast.makeText(AdditionTestActivity.this, "Correct", Toast.LENGTH_SHORT).show();
if (finalCounter < 10) {
initGame();
} else {
testAddTime.cancel();
//Toast.makeText(AdditionTestActivity.this, "True Answer :" + correctCounter + "\n" + "Wrong Attempts" + falseCounter + "\n" + "Time " + toolbarTimeTestAddition.getText().toString(), Toast.LENGTH_SHORT).show();
}
} else {
YoYo.with(Techniques.RubberBand)
.duration(750)
.playOn(tlTestAddAnswer);
etTestAddAnswer.requestFocus();
falseCounter += 1;
Log.d(TAG, "False Answers: " + falseCounter);
etTestAddAnswer.setError("False Answer, \n Try Again..!!");
}
}
} else if (etTestAddAnswer.getText().toString().length() > (String.valueOf((firstDigit + secondDigit)).length())) {
YoYo.with(Techniques.RubberBand)
.duration(750)
.playOn(tlTestAddAnswer);
etTestAddAnswer.requestFocus();
Log.d(TAG, "onTextChanged: " + falseCounter);
//falseCounter++;
etTestAddAnswer.setError("False Answer, \n Try Again..!!");
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
But the false counter is incorrect. Like if i am on fifth question and give my first wrong input, the false counters log is like this:
1
2
3
4
5
It should only increment one. Any ideas??

android: limit of 10 characters per line TextView

I read value from EditText and write it to TextView
editTitle1.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
s = editTitle1.getText().toString();
textTitle1.setText(s);
}
});
And I want that in one line - maximum 10 characters, so if all 20 characters - it's two line in TextView with 10 chars per line. How I can do this?
I try android:maxLength="10" but it does not help
Define a method that returns a string formatted to have 10 characters per line:
public String getTenCharPerLineString(String text){
String tenCharPerLineString = "";
while (text.length() > 10) {
String buffer = text.substring(0, 10);
tenCharPerLineString = tenCharPerLineString + buffer + "/n";
text = text.substring(10);
}
tenCharPerLineString = tenCharPerLineString + text.substring(0);
return tenCharPerLineString;
}
I edited the answer given by ramaral he used wrong escape sequence
public String getTenCharPerLineString(String text){
String tenCharPerLineString = "";
while (text.length() > 10) {
String buffer = text.substring(0, 10);
tenCharPerLineString = tenCharPerLineString + buffer + "\n";
text = text.substring(10);
}
tenCharPerLineString = tenCharPerLineString + text.substring(0);
return tenCharPerLineString;
}
Add the following 2 attributes to the TextView definition:
android:singleLine="false"
android:maxems="10"

Convert drawable to a specific string

I have a chat app which I want to extend with emoticons.
This code is used to insert a smilie in the text:
Spanned cs = Html.fromHtml("<img src ='"+ index +"'/>", imageGetter, null);
int cursorPosition = content.getSelectionStart();
content.getText().insert(cursorPosition, cs);
This is working great. The smilies show up in the textView at the right place.
Now I want to send the text to my server via HTTP.
I would like to store ":)" instead of the image as for ones using an older app version the image can not be displayed. In the new version I convert ":)" to the image before displaying the text. Is there any way to convert the image to a specific string?
if you want to replace your emoticons try this:
EditText et = new EditText(this);
et.setTextSize(24);
et.setHint("this view shows \":)\" as an emoticon, try to type \":)\" somewhere");
final Bitmap smile = BitmapFactory.decodeResource(getResources(), R.drawable.emo_im_happy);
final Pattern pattern = Pattern.compile(":\\)");
TextWatcher watcher = new TextWatcher() {
boolean fastReplace = true;
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//Log.d(TAG, "onTextChanged " + start + " " + before + " " + count);
if (fastReplace) {
if (start > 0 && count > 0) {
String sub = s.subSequence(start - 1, start + 1).toString();
if (sub.equals(":)")) {
Spannable spannable = (Spannable) s;
ImageSpan smileSpan = new ImageSpan(smile);
spannable.setSpan(smileSpan, start-1, start+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
} else {
Spannable spannable = (Spannable) s;
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
int mstart = matcher.start();
int mend = matcher.end();
ImageSpan[] spans = spannable.getSpans(mstart, mend, ImageSpan.class);
Log.d(TAG, "onTextChanged " + mstart + " " + mend + " " + spans.length);
if (spans.length == 0) {
ImageSpan smileSpan = new ImageSpan(smile);
spannable.setSpan(smileSpan, mstart, mend, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
Log.d(TAG, "onTextChanged " + s);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
Log.d(TAG, "afterTextChanged " + s);
}
};
et.addTextChangedListener(watcher );
setContentView(et);
here if fastReplace == true you don't have to scan the whole text but it's only minimal implementation: works only if you type ")" right after typed ":", if fastReplace == false it replaces every occurrence of ":)" with a smiley but it has to scan the whole text so it's a bit slower when text is quite large

Categories

Resources