Convert drawable to a specific string - android

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

Related

how to change the string display

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);

Android EditText change colour of a single word while typing (dynamically)

I have an edit text while typing inside edit text if the word starts with # that particular words color should change ,
i have implemented textwatcher and found that if text starts with # but do not know how to update the color dynamically ,
Have tried SpannableStringBuilder ssb = new SpannableStringBuilder(yourText) But its static , could anyone help me for dynamic implementation
Here is my code
myEditTxt.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) == '#') {
//here i needs to update the typing text color
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
As implemented in this link How to change color of words with hashtags #Muhammed GÜNEŞ suggested
you can modify it according to follow
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
textView.removeTextChangedListener(this);
setTags(textView,s.toString());
textView.setSelection(textView.getText().toString().length());
textView.addTextChangedListener(this);
}
private void setTags(TextView pTextView, String pTagString) {
SpannableString string = new SpannableString(pTagString);
int start = -1;
for (int i = 0; i < pTagString.length(); i++) {
if (pTagString.charAt(i) == '#') {
start = i;
} else if (pTagString.charAt(i) == ' ' || (i == pTagString.length() - 1 && start != -1)) {
if (start != -1) {
if (i == pTagString.length() - 1) {
i++; // case for if hash is last word and there is no
// space after word
}
final String tag = pTagString.substring(start, i);
string.setSpan(new ClickableSpan() {
#Override
public void onClick(View widget) {
Toast.makeText(MainActivity.this,"Click",Toast.LENGTH_LONG).show();
}
#Override
public void updateDrawState(TextPaint ds) {
// link color
ds.setColor(Color.parseColor("#33b5e5"));
ds.setUnderlineText(false);
}
}, start, i, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
start = -1;
}
}
}
pTextView.setMovementMethod(LinkMovementMethod.getInstance());
pTextView.setText(string);
}
it will add color and click event too also u can modify it according o your further requirement
Maybe something like this
#Override
public void onTextChanged(CharSequence text, int start, int before, int count) {
if (text.charAt(start) == '#') {
SpannableString spannableString = new SpannableString(editText.getText().toString());
ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.yourColor));
spannableString.setSpan(foregroundSpan, start,
spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
editText.setText(spannableString);
}
}
If you only want to change "#" char. You can try it:
int index = myEditTxt.getText().toString().indexOf("#");
if (index != -1) {
SpannableString spannable = new
SpannableString(myEditTxt.getText().toString());
ForegroundColorSpan fcs = new ForegroundColorSpan(color);
// Set the text color
spannable.setSpan(fcs, index, index + 1,
Spannable.SPAN_INCLUSIVE_INCLUSIVE);
mEditText.setText(spannable);
}
If you only want to change after and before "#". You can try it in your listener:
if (text.charAt(start) == '#') {
SpannableString spannable = new
SpannableString(myEditTxt.getText().toString());
ForegroundColorSpan fcs = new ForegroundColorSpan(color);
// Set the text color
if (start > 0)
spannable.setSpan(fcs, 0, start -1,
Spannable.SPAN_INCLUSIVE_INCLUSIVE);
if (start < myEditTxt.getText().toString().length())
spannable.setSpan(fcs, start + 1, myEditTxt.getText().toString().length(),
Spannable.SPAN_INCLUSIVE_INCLUSIVE);
mEditText.setText(spannable);
}
Finally found an answer and works as expected .
private int intCount = 0, initialStringLength = 0;
private String strText = "";
on text changed
#Override
public void onTextChanged(CharSequence text, int start, int before, int count) {
String strET = editText.getText().toString();
String[] str = strET.split(" ");
int cnt = 0;
if (text.length() != initialStringLength && text.length() != 0) {
if (!strET.substring(strET.length() - 1).equals(" ")) {
initialStringLength = text.length();
cnt = intCount;
for (int i = 0; i < str.length; i++)
if (str[i].charAt(0) == '#')
strText = strText + " " + "<font color='#EE0000'>" + str[i] + "</font>";
else
strText = strText + " " + str[i];
}
if (intCount == cnt) {
intCount = str.length;
editText.setText(Html.fromHtml(strText));
editText.setSelection(textShareMemories.getText().toString().length());
}
} else {
strText = "";
}
}

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);
}
}
});

android spannable edititext with cursor manipulation

I am trying to implement code highlighting using spanned text and html.fromhtml() function in an edittext than implements text watcher.
The problem occurs when i try to manipulate cursor for custom brackets, the app crashes due to some spannable string setspan error.
How do i use spannable code highlighting and set cursor position adjusting according to the spanned text.
Edit:
The function:
Spanned matchtext(String s)
{
//Pattern p =Pattern.compile(check[0]);
String a=s;
for(int i=0;i<Constants.keyWords.length;i++) {
a = a.replaceAll(Constants.keyWords[i], "<font color=\"#c5c5c5\">" + Constants.keyWords[i] + "</font>");
//a = s.replaceAll(";", "<font color=\"#c5c5c5\">" + ";" + "</font>");
}
Spanned ab = Html.fromHtml(a);
return ab;
}
And the function call:
mCodeEditText.removeTextChangedListener(tt);
bs = matchtext(s.toString());
mCodeEditText.setText(bs);
mCodeEditText.addTextChangedListener(tt);
Edit 2:
This is my new implementation, I just can't get the highlighting to work.
Spannable matchtext(String s, int pos) {
Spannable abc = new SpannableString(s);
for (int i = 0; i < Constants.keyWords.length; i++) {
if (pos - Constants.keyWords[i].length() >= 0) {
int j = s.indexOf(Constants.keyWords[i]);
if (j != -1) {
if ((s.subSequence(j, pos)).equals(Constants.keyWords[i]))
abc.setSpan(new ForegroundColorSpan(Color.BLUE), j, pos, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
}
}
}
return abc;
}

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"

Categories

Resources