I want to set a selected text in an EditText bold.
It's already possible to find out what characters I selected and with getSelectionStart() and getSelectionEnd( ) I know where's the position.
But my problem is, that I want to set the selected Text bold with a Button and don't know how to set the font bold with a String (I only know how to set it with EditText).
So here is my sample code:
fettdruckButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectionStart = fullscreenEdittext.getSelectionStart();
int selectionEnd = fullscreenEdittext.getSelectionEnd();
int differenz = selectionEnd - selectionStart;
String selectedText = fullscreenEdittext.getText().toString().substring(selectionStart, selectionEnd);
Log.d("selectedText", "selectedText " + selectedText + "|" + selectionStart + "|" + selectionEnd);
//fullscreenEdittext.setTypeface(null, Typeface.BOLD);
}
});
Use SpannableStringBuilder.
SpannableStringBuilder stringBuilder = (SpannableStringBuilder) fullscreeneditText.getText();
stringBuilder.setSpan(new StyleSpan(Typeface.BOLD), selectionStart, selectionEnd, 0);
Please note that if you want to do this many times you should remove your original span first.
String completetext=fullscreenEdittext.getText().toString();
int selectionStart = fullscreenEdittext.getSelectionStart();
int selectionEnd = fullscreenEdittext.getSelectionEnd();
int differenz = selectionEnd - selectionStart;
String selectedText = fullscreenEdittext.getText().toString().substring(selectionStart, selectionEnd);
Log.d("selectedText", "selectedText " + selectedText + "|" + selectionStart + "|" + selectionEnd);
String part1=fullscreenEdittext.getText().toString().substring(0, selectionStart);
String part2=fullscreenEdittext.getText().toString().substring(selectionStart, selectionEnd);
String part3=fullscreenEdittext.getText().toString().substring(selectionEnd,completetext.length() );
fullscreenEdittext.setText(Html.fromHtml(part1+"<b>" + part2+ "</b>" +part3));
Use the property of Editext fullscreenEdittext.setText(Html.fromHtml(styledText));
Use html formatting tags <b>selectedText</b> to make the selected text bold.
Please have a look at below code snippet
int selectionStart = fullscreenEdittext.getSelectionStart();
int selectionEnd = fullscreenEdittext.getSelectionEnd();
String startingText = fullscreenEdittext.getText().toString()
.substring(0, selectionStart);
String selectedText = fullscreenEdittext.getText().toString()
.substring(selectionStart, selectionEnd);
String endingText = fullscreenEdittext.getText().toString()
.substring(selectionEnd);
fullscreenEdittext.setText(Html.fromHtml(startingText + "<b>"
+ selectedText + "</b>" + endingText));
Related
working perfect but
when i am highlight text using html then some text can not be view perfect(Hindi text).
android
String str="रिश्ते भले ही कम ही बनाओ लेकिन दिल से निभाओ,\n" +
"क्योंकि आज कल इंसान अच्छाई के चक्कर में अच्छे खो देते है।";
//textview.setText(str);
textview.setText(Html.fromHtml(String.format(colorfulltext(str))), TextView.BufferType.SPANNABLE);
// highlight text
public String colorfulltext(String text) {
String[] colors = new String[]{"#fdc113", "#fdc113", "#fdc113","#fdc113", "#fdc113" ,"#fcfcfc", "#fcfcfc", "#fcfcfc", "#fcfcfc", "#fcfcfc", "#fcfcfc", "#fcfcfc", "#fcfcfc", "#fcfcfc","#fcfcfc","#fcfcfc","#fcfcfc","#fcfcfc"};
StringBuilder finals = new StringBuilder();
int size = colors.length;
int k = 0;
for (int item = 0; item < text.length(); item++) {
if (k >= size) {
k = 0;
}
finals.append("<font color='" + colors[k] + "'>" + text.charAt(item) + "</font>");
k++;
}
return finals.toString();
}
screen
Why do you convert a String to html to apply fontcolor for a static text??
You have to follow the following steps:
Create entries in Strings.xml for each text. For instance, रिश्ते
has a different color and needs to be a separate entry in
strings.xml.
add this to a Util class:
public static void addColoredPart(SpannableStringBuilder ssb,
String word, int color,String... texts) {
for(String text : texts) {
if (word != null) {
int idx1 = text.indexOf(word);
if (idx1 == -1) {
return;
}
int idx2 = idx1 + word.length();
ssb.setSpan(new ForegroundColorSpan(color), idx1, idx2,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
apply style the following way:
String string1 = context.getString(R.string.String_id1)
String string2 = context.getString(R.string.String_id2)
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
spannableStringBuilder.append(string2)
spannableStringBuilder.append(string2)
SpannableUtil.addColoredPart(
spannableStringBuilder,
spannableStringBuilder.toString(), color, string1, string2);
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;
}
How ist it possible to colour the newText "e"?
public void onClick(View v) {
String text = tw.getText().toString();
int n = 4;
String newText = text.substring(0, n) + "e" + text.substring(n + 1);
tw.setText(newText);
You need to use a ForegroundColorSpan
final String text = "something something text";
final int n = 4;
final String newText = text.substring(0, n) + "e" + text.substring(n + 1);
final ForegroundColorSpan fcs = new ForegroundColorSpan(Color.RED);
final SpannableString ss = new SpannableString(newText);
ss.setSpan(fcs, n, n + 1, 0);
tv.setText(ss);
yes, if you formate the String with html
You need to use Html.fromHtml() to use HTML in your XML Strings. Simply referencing a String with HTML in your layout XML will not work.
For example:
String text = "<font color=#cc0029>Exempl</font> <font color=#ffcc00>e</font>";
myTextView.setText(Html.fromHtml(text);
Hi iam trying to change part of the text in textview to some color but iam unble to achieve it
i tried fromHtml , spannable and different methoda but its still not working.
My tries are as below:
try1
Spannable wordtoSpan = Spannable.Factory.getInstance().newSpannable("text 6 Months(180 days) or 8,000 kilometers.");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 5, 15, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(wordtoSpan);
try2
String str = "#Second #Service:6 Months(180 days) or 8,000 kilometers.";
String[] str_array = str .split(" ");
boolean isExists = false;
for (int i = 0; i < str_array.length; i++) {
for (int j = 0; j < i; j++) {
if (str_array[j].equals(str_array[i])) {
isExists = true;
}
}
if (str_array[i].startsWith("#") && !isExists) {
str = str .replace(str_array[i],
"<font color='#8A0A0A'>" + str_array[i]
+ "</font>");
} else if (str_array[i].contains("#")) {
str = str .replaceAll(str_array[i],
"<font color='#000000'><b>" + str_array[i]
+ "</b></font>");
}
}
tv.setText(Html.fromHtml(str));
}
try3
myTextView.setText(Html.fromHtml(text + "<font color=white>" + CepVizyon.getPhoneCode() + "</font><br><br>"
+ getText(R.string.currentversion) + CepVizyon.getLicenseText()));
try4
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//method1
TextView tv = (TextView) findViewById(R.id.service);
tv.setText(Html.fromHtml("<font color=\"#FFFFFF\">" + "give your string here long long longlong" + "</font>" + "<font color=\"#47a842\"></font>"));
//method 2
//SpannableStringBuilder WordtoSpan = new SpannableStringBuilder("give your string here long long longlong");
//WordtoSpan.setSpan(new BackgroundColorSpan(Color.YELLOW),0,5,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//tv.setText(WordtoSpan);
}
Any help is really appreciated.Thank you
Try like this. The below code is perfectly working for me, i have tested it.
TextView ttt = (TextView) findViewById(R.id.textView11);
String styledText = "This is <font color='red'>simple</font>.";
ttt.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);
and here is output.
Try this it is running in my app perfectly.. May be it help you too
SpannableStringBuilder WordtoSpan = new SpannableStringBuilder(give your string here);
WordtoSpan.setSpan(new BackgroundColorSpan(Color.YELLOW),starting Index, and the index of text from which you want to highlight you text,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView.setText(WordtoSpan);
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