I am selecting a part of the TextView and on click of a "highlight" button, I am sending the start and the end index of selection to the database. Then I am loading all the start and end indexes from db and changing the color of text between them.
The problem is after once or twice, the app is changing the color of text that is not in selection.. and the selected part remains unchanged.
MY CODE:
When user selects and presses the highlight button
int i=contentText.getSelectionStart();
int j=contentText.getSelectionEnd();
db.insertHiglightIndex(String.valueOf(i),String.valueOf(j));
setHighlightedText();
The setHighlightedText() method..
String fullText=contentText.getText().toString();
for(int i=0; i<db.getAllStartIndex().size();i++){
String a=fullText.substring(Integer.parseInt(db.getAllStartIndex().get(i)),Integer.parseInt(db.getAllEndIndex().get(i)));
fullText = fullText.replace(a, "<font color='red'>"+a+"</font>");
}
contentText.setText(Html.fromHtml(fullText), TextView.BufferType.SPANNABLE);
MY SCREENSHOTS.
The selection:
The Result:
Clearly the selected area is from "Garrick" to "Bart", and the result is from "entity" to "2012"
I am not able to understand why is this happening. I think there is some problem with this <font color='red'>"+a+"</font> line.
Thank you
It got wrong indexed because There is already added <font color='red'> in the beginning, So that in second time This tag is also counted as a part of string, So I suggest creating a new temporary String, assign same text to the String but after replacing the previous font tag it held. Use this syntax to remove previous font tag from originalString
String tempString = originalString.replaceAll("[<](/)?font[^>]*[>]", "");
After that work with only tempString. That means again add every previous font tag you have to tempString and set that text.
In next time again do the same first remove all font tag and again add all of them back in tempString as well as current selection using same loop you are using currently.
You have wrong indexes because you are modifying the fullText content within the loop.
Taking a look at this example you can figure it:
final TextView tv = (TextView) findViewById(R.id.textView);
tv.setText( "abcdefghijklmnopqrstuvwxyz0123456789");
String fullText= tv.getText().toString();
// your first iteration
String a = fullText.substring(1,3);
// a contains "ab"
fullText = fullText.replace(a, "<font color='red'>"+a+"</font>");
After the first iteration full text contains now
a<font color='red'>bc</font>defghijklmnopqrstuvwxyz0123456789"
Then the substring() in the second iteration won't returns the substring base on your initial content.
If you want to be able to have multiple substrings colored in red you can try this:
String fullText = contentText.getText().toString();
StringBuilder result = new StringBuilder();
for(int i=0; i < db.getAllStartIndex().size(); i++){
fullText = applyFont(result, fullText, Integer.parseInt(db.getAllStartIndex().get(i)), Integer.parseInt(db.getAllEndIndex().get(i)));
}
// Add here the remaining content
result.append(fullText);
contentText.setText(Html.fromHtml(result.toString()), TextView.BufferType.SPANNABLE);
private String applyFont(StringBuilder result, String source, int from, int to){
result.append(source.substring(0, from));
result.append("<font color='red'>");
result.append(source.substring(from, to));
result.append("</font>");
return source.substring(to, source.length());
}
Related
I want to display the text in vertical text view (i.e. characters should be placed one below another as below)
a
b
c
d
I wish to do this in a single text view.
We can turn the entire text by using android:toDegrees="-90" or "90" but i want to display as shown above which is not achieved with android:toDegress tag.
Appreciate your help!
UPDATE
I will get the String from another app through AIDL which is subjected to change as per the sender, in addition, he will send me a flag to display the text in a vertical or horizontal direction. Based on the flag I should display accordingly. I have no problem with a horizontal view as it is the default one but to display it in vertical(as shown above) I need help.
If String is Dynamic then you can add \n after each character.
private String build(String str){
if(!TextUtils.isEmpty(str)) {
StringBuilder builder = new StringBuilder();
builder.append(str.charAt(0));
for (int i = 1; i < str.length(); i++) {
builder.append("\n"+str.charAt(i));
}
return builder.toString();
}
return "";
}
textView.setText(build("abcd"));
It will show vertically. This way text can go out of Bound so you should make TextView scrollable in this case.
You can add line break to your string with either \n or <br>
With \n:
<string name="sample_string">a\nb\nc\nd</string>
textView.setText(R.string.sample_string)
With <br>:
<string name="sample_string"><![CDATA[a<br />b<br />c<br />d]]></string>
textView.setText(Html.fromHtml(context.getString(R.string.sample_string))
I have a TextView and I can search some words, so that they're marked.
The TextView is named textView and it shows the text, I have an EditText Etxt to get the searched word and a Button to start the search. The code above is the code of the search. The app marks all found words big and italic. And I have a TextView text_total which shows the number of found words.
The problem: But if there is a searched word in the text below the shown screen, you must scroll and find the marked word:
int total = 0;
String word_search = Etxt.getText().toString().trim().toLowerCase();
String fullTxt = textView.getText().toString();
String[] array = fullTxt.split("\n");
String word;
StringBuilder st = new StringBuilder();
for (int i = 0; i < array.length; i++) {
word = array[i];
if (word.toLowerCase().contains(word_search)) {
String abc = word.trim();
st.append("<b><i>" + abc + "</i></b>");
total++;
} else {
st.append(word);
}
st.append("<br>");
}
textView.setText(Html.fromHtml("" + st));
text_total.setText("Ergebnisse: " + total);
Now, I have a problem because the text is too long to see all search results. I want that I have a 'back' and a 'next' button and the view goes to the next result if I click the next button and that the the found word goes automatically to the shown screen.
Does anyone know how to code this?
That's very important. Thanks for help!
Try this.
Put all the finded words in a list
List words= new ArrayList();
Add the words to the list
words.add(word_search);
Finally in next and previous buttons, you need to check the positions of the words in the list
words.get(position)
See how in this link
1.I am getting data from server storing inside string Array.
2.then i want to show in Android TextView ,each TextView line should Contain 2 strings(Like Skill Sets) from String array.
3.then need to add cross Image in right side of the Textview.
please help me, how to achieve this.
String mystring = "This is my first sentence";
String arr[] = mystring.split(" ", 3);
String firstWord = arr[0]; //This
String secondWord = arr[1]; //is
String theRest = arr[2]; //my first sentence
yourtextview.setText(firstWord +" "+ secondWord);
and regarding for Image in right side of the Textview put this in ur txtview'sxml.
android:drawableRight="#drawable/image"
In my android application I am using spinner for selecting data.. and I created string array for strings that to be displayed in spinner. I put all the details in strings folder. I wanted the selected text t be displayed in edit text once the user selected item..
For example : spinner is used to select country codes suppose user selected USA
then the selected text will be like this
United States of America,+001
I don't need t take all the text and display it in edit text. I need only the text after comma, that is +001. So is there any way to get the text after the comma only
Spinner spinner = (Spinner)findViewById(R.id.spinner);
String text = spinner.getSelectedItem().toString();
I know this will display all text I want only text that dislpaying after comma
You can split your text on the comma:
String text = spinner.getSelectedItem().toString();
String[] splited_text = text.split(",");
text = splited_text[1];
Suppose the text is in a string name text. use this:
String[] temp = text.split(",")
String code = temp[1]; //+001 the code after , temp[0] contains the rest
String seperated[] = spinner.getSelectedItem().toString().split(",");
text = seperated[1];
This will return only "+001".
String code = text.substring(text.indexOf(','));
This is how to get string after last comma:
String founded;
Pattern p = Pattern.compile(".*,\\s*(.*)");
String dd = (String) "Your string, really, really2";
Matcher m = p.matcher(dd);
if (m.find()) {
founded = m.group(1); //returns "really2"
}
I want to insert a constant string into an EditText by the press of a button. The string should be inserted at the current position in the EditText.
If I use EditText.append the text gets inserted at the end of the EditText.
How can I do that? I couldn't find a suitable method.
Cpt.Ohlund gave me the right hint. I solved it, now, partly with using EditText.getSelectionStart(), but I realized that you can also replace the selected text with the same expression and you don't need String.subString() for that.
int start = Math.max(myEditText.getSelectionStart(), 0);
int end = Math.max(myEditText.getSelectionEnd(), 0);
myEditText.getText().replace(Math.min(start, end), Math.max(start, end),
textToInsert, 0, textToInsert.length());
This works for both, inserting a text at the current position and replacing whatever text is selected by the user. The Math.max() is necessary in the first and second line because, if there is no selection or cursor in the EditText, getSelectionStart() and getSelectionEnd() will both return -1. The Math.min() and Math.max() in the third line is necessary because the user could have selected the text backwards and thus start would have a higher value than end which is not allowed for Editable.replace().
This seems simpler:
yourEditText.getText().insert(yourEditText.getSelectionStart(), "fizzbuzz");
However, Manuel's answer might be better if you want to replace any selected text with the inserted text.
Try using EditText.getSelectionStart() to get the current position of the cursor. Then you can use String.subString to get the text before and after the cursor and insert your text in the middle.
I think this function will help for you :
public void insertConstantStr(String insertStr) {
String oriContent = editText.getText().toString();
int index = editText.getSelectionStart() >= 0 ? editText.getSelectionStart() : 0;
StringBuilder sBuilder = new StringBuilder(oriContent);
sBuilder.insert(index, insertStr);
editText.setText(sBuilder.toString());
editText.setSelection(index + insertStr.length());
}
For Kotlin simply do that:
editText.text.insert(editText.selectionStart, "Your Text Here")
Editable editable = new SpannableStringBuilder("Pass a string here");
yourEditText.text = editable;