How to use removeSpan() on android textview? - java

Pardon me if I'm asking a dumb question but I would like to know how to remove a span from text in my textview. This is how my span method looks like.
public CharSequence setTextStyleItalic(CharSequence text) {
StyleSpan style = new StyleSpan(Typeface.ITALIC);
SpannableString str = new SpannableString(text);
str.setSpan(style, 0, text.length(), 0);
return str;
}
and this is how i call it.
tvTitle.setText(setTextStyleItalic(tvTitle.getText()));
I would really like to know how to remove this italic span in java using removeSpan() please.

Get the text of the TextView and cast it to SpannableString then you can use the getSpans(int queryStart, int queryEnd, Class<T> kind) method to iterate over those spans and remove them
SpannableString ss=(SpannableString)txtView.getText();
ForegroundColorSpan[] spans=ss.getSpans(0, txtView.getText().length(), ForegroundColorSpan.class);
for(int i=0; i<spans.length; i++){
ss.removeSpan(spans[i]);
}

First get text from your span using getSpans()
removeTextSpan = tvTitle.getSpans(0, tvTitle.getText().length(),ForegroundColorSpan.class);
for (int i = 0; i < removeTextSpan.length; i++)
tvTitle.removeSpan(removeTextSpan[i]);
i think this will help

Set and remove span for ITALIC
val spannable: Spannable = SpannableStringBuilder(editText.text)
val start = editText.selectionStart
val end = editText.selectionEnd
val allSpans: Array<StyleSpan> = spannable.getSpans(0,
spannable.length, StyleSpan::class.java)
if (doItalic) {
spannable.setSpan(
StyleSpan(ITALIC), start, end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
} else {
for (span in allSpans) {
if (span.style == ITALIC)
spannable.removeSpan(span)
}
}
editText.setText(spannable)

Related

How to get StrikeThrough on a String ? Not a TextView, EditText or a View. But like String a = "my text" and then pass it to SQLite as a String

I have this method which works fine for an EditText or a view.
public SpannableString strikeThrough(String txt){
SpannableString spannableString = new SpannableString(txt);
StrikethroughSpan strikethroughSpan = new StrikethroughSpan();
spannableString.setSpan(strikethroughSpan,0, txt.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableString;
}
EditText etChecklistItem = checklistView.findViewById(R.id.et_checklist_item);
etChecklistItem.setText(strikeThrough(etChecklistItem.getText().toString()));
But my problem is after that, the text doesn't have StrikeThrough.
StringBuilder stringBuilderItem = new StringBuilder();
for( String list : itemslist) {
stringBuilderItem.append(list);
stringBuilderItem.append("\n");
}
String text = stringBuilderItem.toString();
strikeThrough(text);
dbHelper.insertChecklist(text);
When I get the data in RecyclerView, it would not be in Strikethrough.
Instead of storing a strike-through string inside the array, Create a class having two members a String and a boolean, and make the boolean true for the string you want to strike through.
class Message {
private String str;
private boolean strike;
public Message (String str, boolean strike) {
this.str = str;
this.strike = strike;
}
// getters and setters
}
and make string strike through when you're showing it on the screen
ArrayList<Message> arr = new ArrayList<>();
for (Message msg: arr) {
if (arr.getStrike()) {
// make string strikethrough
} else {
// keep as it is
}
}
To strike through a string in TextView
Method 1
textView.setText("I want like that")
textView.setPaintFlags(tv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
Method 2: If you want to strike through only a part of the text then use
String str = "I want like that";
SpannableStringBuilder builder = new SpannableStringBuilder(str);
StrikethroughSpan strikethroughSpan = new StrikethroughSpan();
builder.setSpan(
strikethroughSpan,
0, // Start
4, // End (exclusive)
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE // Text changes will not reflect in the strike changing
);
textView.setText(spanBuilder);
Method 3: If you want to strike through text in strings.xml
<string name="yourName"><strike>I want like that</strike></string>
references: [1]
Just Checkout this Code
First you need to initialise you edit text or text view
textView = findViewById(R.id.textView);
textView.setText("Hello World");
textView.setPaintFlags(textView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
I hope this will help you, if any problem just comment down

obj.getString - Styling in android studio, possible?

Looking to style (bold, italic etc.) "quote" and "name", but have tried several potential solutions with no luck:
private void settextView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String[] tasks = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
tasks[i] = obj.getString("quote") + "\n\n" + obj.getString("name");
textView.setText(tasks[0]);
setBtnCopyOnClick(tasks[0]); //Here
String a = "quote";
SpannableString spanned = new SpannableString(a);
spanned.setSpan(new UnderlineSpan(), 1, a.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
They both generate in the same textView, so unfortunately I can only style all, or not at all.
If you are looking to style only specific parts of text you should be using spans. The Android Developers site has good documentation on this which you can read here.
For your particular use case pay most attention to the StyleSpan which allows you to set Typeface flags.
For example:
String a = "underlined text";
String b = " normal text";
SpannableString spanned = new SpannableString(a + b);
spanned.setSpan(new UnderlineSpan(), 0, a.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

TextView Numbers shown in English in Persian font

I am loading a string which contains some number (all in Persian) into an android TextView. Everything was fine until I changed my custom font, numbers of text shown as English number.
Expected : ۱۲۳۴
Received : 1234
I know that my new font support Persian number. When I change the number locale using code below the number shown correctly.
NumberFormat numberFormat = NumberFormat.getInstance(new Locale("fa", "IR"));
String newNumber = numberFormat.format(number);
The problem is I have a string and it's hard to find the numeric part and change it. also my previous font works fine and I can't understand what's the problem with this font.
Any Idea how to globally solve this problem for all textview, or at least for a string?
Try to use this method:
private String setPersianNumbers(String str) {
return str
.replace("0", "۰")
.replace("1", "۱")
.replace("2", "۲")
.replace("3", "۳")
.replace("4", "۴")
.replace("5", "۵")
.replace("6", "۶")
.replace("7", "۷")
.replace("8", "۸")
.replace("9", "۹");
}
You can use this
String NumberString = String.format("%d", NumberInteger);
123 will become ١٢٣
Use this code for show Hegira date in Persian number:
String farsiDate = "1398/11/3";
farsiDate = farsiDate
.replace('0', '٠')
.replace('1', '١')
.replace('2', '٢')
.replace('3', '٣')
.replace('4', '٤')
.replace('5', '٥')
.replace('6', '٦')
.replace('7', '٧')
.replace('8', '٨')
.replace('9', '٩');
dateText.setText(farsiDate);
You'll have to translate it yourself. TextFormat does not automatically translate from arabic digits to any other language's, because that's actually not what people usually want. Each of those digits have their own character codes, a simple walk of the string and replacing them with the appropriate persian code would be sufficient.
private static String[] persianNumbers = new String[]{ "۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹" };
public static String PerisanNumber(String text) {
if (text.length() == 0) {
return "";
}
String out = "";
int length = text.length();
for (int i = 0; i < length; i++) {
char c = text.charAt(i);
if ('0' <= c && c <= '9') {
int number = Integer.parseInt(String.valueOf(c));
out += persianNumbers[number];
} else if (c == '٫') {
out += '،';
} else {
out += c;
}
}
return out;
}}
and after that u can use it like below vlock
TextView textView = findViewById(R.id.text_view);
textView.setText(PersianDigitConverter.PerisanNumber("این یک نمونه است ۱۲ "));
In JS, you can use the function below:
function toPersianDigits(inputValue: any) {
let value = `${inputValue}`;
const charCodeZero = '۰'.charCodeAt(0);
return String(value).replace(/[0-9]/g, w =>
String.fromCharCode(w.charCodeAt(0) + charCodeZero - 48),
);
}
export {toPersianDigits};

How to retain multiple occurrences of same string get selected within same styled text content?

How to retain multiple occurrences of same string get selected within same styled text content? Single occurrence can be selected using setSelection(). Is there any similar options?
Use StyleRange to set multiple occurrences of the string.
Snippet:
String searchKey = "hello";
String content = styledText.getText(); // StyledText instance
int index = content.indexOf(searchKey, 0);
do {
if (index != -1) {
StyleRange styleRange = new StyleRange(index, searchKey.length(), Display.getCurrent().getSystemColor(
SWT.COLOR_BLACK), Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW));
styledText.setStyleRange(styleRange);
index = content.indexOf(searchKey, index + 1);
} else {
System.out.println("End of search");
break;
}
} while (index != -1);
Refer this article an examples here on style ranges.

Searching for words in textarea

I am building a custom a find and replace in java. I browse a text file and load the contents in a textarea. Now I have a textBox, where I input a text that needs to be searched.
What is the best way to search the text. I know a way using string.indexOf(), but I also need highlighting. So please help me out.
First of all read Text and New Lines for information on how to get the text to search.
Then to highlight the text your find you need to use a Highlighter. The code is something like:
Highlighter.HighlightPainter painter =
new DefaultHighlighter.DefaultHighlightPainter( Color.cyan );
int offset = text.indexOf(searchWord);
int length = searchWord.length();
while ( offset != -1)
{
try
{
textPane.getHighlighter().addHighlight(offset, offset + length, painter);
offset = text.indexOf(searchWord, offset+1);
}
catch(BadLocationException ble) { System.out.println(ble); }
}
indexOf is the easiest way, but might not be the fastest way.
Why isn't indexOf working for you? You will get the index of the match, and you know the length of the match, so just highlight the text that matched.
I am having the same problem with my text editor. I didn't use a highlighter though, I used
textArea.select(int i1, int i2); //where i1 is where your selection begins and i2 is where it ends.
also an easy way to find and replace is:
textArea.setText(textArea.getText().replaceAll(String string1, String string2));
final String inputValue = JOptionPane.showInputDialog("Find What?");
final int l1 = jTextArea1.getText().indexOf(inputValue);
final int l2 = inputValue.length();
if (l1 == -1) {
JOptionPane.showMessageDialog(null, "Search Value Not Found");
} else {
jTextArea1.select(l1, l2+l1);
}
if (e.getSource() == btnSearch && !searchWord.getText().isEmpty()) {
Highlighter.HighlightPainter painter =
new DefaultHighlighter.DefaultHighlightPainter( Color.cyan );
templateArea.getHighlighter().removeAllHighlights();
int offset = templateArea.getText().indexOf(searchWord.getText());
int length = searchWord.getText().length();
while ( offset != -1)
{
try
{
templateArea.getHighlighter().addHighlight(offset, offset + length, painter);
offset = templateArea.getText().indexOf(searchWord.getText(), offset+1);
}
catch(BadLocationException exception) { System.out.println(exception); }
}
}
}

Categories