Android rich text Mark Down - java

I'm looking for a library or optimized examples on using
Mark Down to create Rich Text.
For example, something to turn:
1 - *Bold* -> Bold
2 - _Italic_ -> Italic
Long example:
3 - _Hello_ *World* -> Hello World
And so on.
I've seen many apps use it, like Discord, Whatsapp, Skype.
I've done something similar, but I know it's not optimized and can lead to runtime errors.

You don't need any extra library...
Just have a look into android.text.SpannableStringBuilder...
This will allow you to get text features like:
Make it larger
Bold
Underline
Italicize
Strike-through
Colored
Highlighted
Show as superscript
Show as subscript
Show as a link
Make it clickable.
Here you have an example on how to apply a Bold style on a word in a TextView :
String text = "This is an example with a Bold word...";
// Initialize a new SpannableStringBuilder instance
SpannableStringBuilder strb = new SpannableStringBuilder(text);
// Initialize a new StyleSpan to display bold text
StyleSpan bSpan = new StyleSpan(Typeface.BOLD);
// The index where to start applying the Bold Span
int idx = text.indexOf("Bold");
strb.setSpan(
bSpan, // Span to add
idx, // Start of the span
idx + 4, // End of the span
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
);
// Display the spannable text to yourTextView
yourTextView.setText(ssBuilder);

SpannableStringBuilder str = new SpannableStringBuilder("Your awesome text");
str.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD), start_int, end_int, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView tv=new TextView(context);
tv.setText(str);

I think you have to look for library that support mark down
https://github.com/tiagohm/MarkdownView
https://github.com/noties/Markwon
https://github.com/IonicaBizau/medium-editor-markdown

Related

How to delete one word from a android textview (multiple lines) without affecting the alignment/position of other words

I have a android textview and I am setting 10 word sentence to it.
Now, I need to delete one word (say 4th word) without affecting the remaining word's positions/alignment.
Please refer below image. Also note, if am replacing that particular word with whitespaces, still alignment is slightly changing for remaining word's, as each character taking different width.
How can I achieve it using textview? Any help is much appreciated. Thanks.
You can use a SpannableString to apply the color of the background (looks like white in your picture) to the letters which should vanish.
If you want to apply the effect to the fourth word ("sample") then you can write
val startOfWord = 11
val endOfWord = 16
val spannable = SpannableString(“This is my sample text goes ...”)
spannable.setSpan(ForegroundColorSpan(Color.WHITE),
startOfWord, endOfWord + 1,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
exampleTextView.text = spannable
See also Spantastic text styling with Spans by Florina Muntenescu
Here is an algorithm
First: use StaticLayout.getDesiredWidth() for calculating the width of the word that you want to be hidden
Second: use the same method to calculate the width of the space character.
Third: get the no. of needed spaces by dividing the first on the second.
Let's code:
Note: I used the same text as you put.
<TextView
android:id="#+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is my sample text goes here\n with multiple words and lines and center aligned" />
Java
TextView textView = findViewById(R.id.textview);
String originalText = textView.getText().toString();
// Get the word that you want to replace
String text = originalText.substring(11, 18);
// Step 1: Get the word width
float wordWidth = StaticLayout.getDesiredWidth(text, new TextPaint());
// Step 2: Get the space width
float spaceWidth = StaticLayout.getDesiredWidth(" ", new TextPaint());
// Step 3: Get the needed no. of spaces
float nSpaces = wordWidth / spaceWidth;
// Step 4: Replace the word with the no. of spaces
StringBuilder newText = new StringBuilder(originalText.substring(0, 11));
for (int i = 0; i < nSpaces; i++) {
newText.append(" ");
}
newText.append(originalText.substring(18));
textView.setText(newText);
Result

How to create highlight textview like Adobe Reader or Medium?

guys.
I need a little bit inspiration right here. I want to create an application that have a highlight feature, just like screenshot below. But, I don't have an idea how to do this. I think Spannable TextView only can't just help me. Do you have some idea?
Thank you.
Example of highlight menu in Medium App
You can use SpannableString
To highlight specific text use this method.
private void highlightString(String input) {
//Get the text from text view and create a spannable string
SpannableString spannableString = new SpannableString(mTextView.getText());
//Get the previous spans and remove them
BackgroundColorSpan[] backgroundSpans = spannableString.getSpans(0, spannableString.length(), BackgroundColorSpan.class);
for (BackgroundColorSpan span: backgroundSpans) {
spannableString.removeSpan(span);
}
//Search for all occurrences of the keyword in the string
int indexOfKeyword = spannableString.toString().indexOf(input);
while (indexOfKeyword > 0) {
//Create a background color span on the keyword
spannableString.setSpan(new BackgroundColorSpan(Color.YELLOW), indexOfKeyword, indexOfKeyword + input.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//Get the next index of the keyword
indexOfKeyword = spannableString.toString().indexOf(input, indexOfKeyword + input.length());
}
//Set the final text on TextView
mTextView.setText(spannableString);}

Android edit text italic issue

I am trying to build a feature where users can select a text in an Edit text and make the text italic or bold by clicking buttons in a small toolbar. I wrote some code in android studio but there is an issue.
public void bold(EditText text){
int start = text.getSelectionStart();
int end = text.getSelectionEnd();
CharacterStyle style = new StyleSpan(Typeface.BOLD);
SpannableStringBuilder sb = new SpannableStringBuilder(text.getText().toString());
sb.setSpan(style, start, end, 0);
text.setText(sb);
}
When user click bold button, it calls the bold() function and bolds the selected text.but if i change the selection and click italics, it italics the selected text but deletes the bold style i already applied to the edit text.
For example
exampleone exampletwo (bolds the text)
But if click select exampletwo and click italic
it becomes
exampleone exampletwo
I lost the style of the first word in the Edittext.
How can i fix this issue ?
SpannableStringBuilder ssb = newSpannableStringBuilder(bodyView.getText());
cs = new StyleSpan(Typeface.BOLD);
ssb.setSpan(cs, start, end, 1);
cs = new StyleSpan(Typeface.ITALIC);
ssb.setSpan(cs, start, end, 1);
I think you should use same Spannablestringbuilder for bold and italic.
It works for me.

How to write a Highlighted text inside a Textview

Can you guys tell me how to write a java code inside a textview and i want it colored just like i'm writing a java code.
I found an example that is composed of 2 types of text and I think that both of them are TextView but the seconde one contain Highlight text and that green bar at left , can you guys tell how to do it .
( sorry i can't upload a picture )
Try this,
public static void setText(TextView textView, String text) {
Spannable spannable = new SpannableString(text);
// For Foreground Highlight
spannable.setSpan(new ForegroundColorSpan(fromColor(ColorCode)), highlight.start, highlight.end, 0);
// For Background Highlight
spannable.setSpan(new BackgroundColorSpan(fromColor(ColorCode)), highlight.start, highlight.end, 0);
textView.setText(spannable);
}
Try this,
TextView TV = (TextView)findViewById(R.id.mytextview01);
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TV.setText(wordtoSpan);
Original answer here

Getting the font letter and color from a Styled Document/Text Pane

Lately I have been using Style Constants, Styled Documents and Text Pane. I know that you can edit a part of the text that you highlight/select showing it in the code below
StyledDocument doc = this.tpText.getStyledDocument();
Style style = this.tpText.addStyle("stylish", null);
StyleConstants.setForeground(style, color.BLACK);
StyleConstants.setFontFamily(style, "Arial");
doc.setCharacterAttributes(this.tpText.getSelectionStart(), this.tpText.getSelectionEnd() - this.tpText.getSelectionStart(), this.tpText.getStyle("stylish"), true);//This is the piece of code (last line) that will set all the attributes to the highlited text.
As an example, if the user highlights/selects "o worl" in "hello world", just the "o worl" will be changed to color black and the font letter will be Arial.
Now, my question is: how can you get the font letter and color from a highlihted/selected text? I want to know how can I save that in seperate variables (one for color and the other for the font letter).
Ok, after doing more research I found out the answer.
doc = this.tpText.getStyledDocument();
Element element = doc.getCharacterElement(this.tpText.getSelectionStart());
AttributeSet as = element.getAttributes();
colour = StyleConstants.getForeground(as);
The only downside I see about this Style Constant method is that it will only recognize the first character attribute and overwrite/ignore the other ones. Maybe with a loop I can do it.

Categories