class ClickToCopySpan extends ClickableSpan {
@Override
public void onClick(@NonNull View widget) {
if(widget instanceof TextView) {
Spanned spanned = (Spanned) ((TextView) widget).getText();
int start = spanned.getSpanStart(this);
int end = spanned.getSpanEnd(this);
String text = spanned.subSequence(start, end).toString().trim();
GlobalUtils.copyToClipboard(context, text);
GlobalUtils.showToast(context, context.getString(R.string.toast_code_clipboard), false);
}
}
@Override
public void updateDrawState(@NonNull TextPaint ds) { }
}
class CopyIconSpan implements LeadingMarginSpan {
@Override
public int getLeadingMargin(boolean first) { return 0; }
@Override
public void drawLeadingMargin(@NonNull Canvas canvas, @NonNull Paint p, int x, int dir, int top, int baseline, int bottom, @NonNull CharSequence text, int start, int end, boolean first, @NonNull Layout layout) {
if (!LeadingMarginUtils.selfStart(start, text, this)) return; // 仅处理第一行
int save = canvas.save();
try {
Paint paint = new Paint();
String textToDraw = context.getString(R.string.text_copy_code_notice);
paint.setTextSize(GlobalUtils.dpToPx(context, 14));
paint.setColor(0x50000000);
Rect bounds = new Rect();
paint.getTextBounds(textToDraw, 0, textToDraw.length(), bounds);
int y = top + bounds.height() + GlobalUtils.dpToPx(context, 4);
int x1 = layout.getWidth() - bounds.width() - GlobalUtils.dpToPx(context, 8);
if(layout.getWidth() > bounds.width() + GlobalUtils.dpToPx(context, 16))
canvas.drawText(textToDraw, x1, y, paint);
} finally {
canvas.restoreToCount(save);
}
}
}
public MarkdownRenderer(Context context) {
this.context = context;
markwon = Markwon.builder(context)
.usePlugin(SyntaxHighlightPlugin.create(new Prism4j(new GrammarLocatorDef()), Prism4jThemeDefault.create(0)))
.usePlugin(new AbstractMarkwonPlugin() {
@Override
public void configureSpansFactory(@NonNull MarkwonSpansFactory.Builder builder) {
builder.appendFactory(FencedCodeBlock.class, (configuration, props) -> new ClickToCopySpan());
builder.appendFactory(FencedCodeBlock.class, (configuration, props) -> new CopyIconSpan());
}
})
.usePlugin(JLatexMathPlugin.create(40, builder -> builder.inlinesEnabled(true)))
.usePlugin(ImagesPlugin.create())
.usePlugin(MarkwonInlineParserPlugin.create())
.usePlugin(LinkifyPlugin.create())
.usePlugin(new AbstractMarkwonPlugin() {
@NonNull
@Override
public String processMarkdown(@NonNull String markdown) { // 预处理MD文本
List<String> sepList = new ArrayList<>(Arrays.asList(markdown.split("```", -1)));
for (int i = 0; i < sepList.size(); i += 2) { // 跳过代码块不处理
// 解决仅能渲染“$$...$$”公式的问题
String regexDollar = "(?<!\\$)\\$(?!\\$)([^\\n]*?)(?<!\\$)\\$(?!\\$)"; // 匹配单行内的“$...$”
String regexBrackets = "(?s)\\\\\\[(.*?)\\\\\\]"; // 跨行匹配“\[...\]”
String regexParentheses = "\\\\\\(([^\\n]*?)\\\\\\)"; // 匹配单行内的“\(...\)”
String latexReplacement = "\\$\\$$1\\$\\$"; // 替换为“$$...$$”
// 为图片添加指向同一URL的链接
String regexImage = "!\\[(.*?)\\]\\((.*?)\\)"; // 匹配“”
String imageReplacement = "[$0]($2)"; // 替换为“[](...)”
// 进行替换
sepList.set(i, sepList.get(i).replaceAll(regexDollar, latexReplacement)
.replaceAll(regexBrackets, latexReplacement)
.replaceAll(regexParentheses, latexReplacement)
.replaceAll(regexImage, imageReplacement));
}
return String.join("```", sepList);
}
})
.usePlugin(new AbstractMarkwonPlugin() { // 设置图片大小
@Override
public void configureConfiguration(@NonNull MarkwonConfiguration.Builder builder) {
builder.imageSizeResolver(new ImageSizeResolverDef(){
@NonNull @Override
protected Rect resolveImageSize(@Nullable ImageSize imageSize, @NonNull Rect imageBounds, int canvasWidth, float textSize) {
int maxSize = GlobalUtils.dpToPx(context, 120);
if(imageBounds.width() > maxSize || imageBounds.height() > maxSize) {
float ratio = Math.min((float)maxSize / imageBounds.width(), (float)maxSize / imageBounds.height());
imageBounds.right = imageBounds.left + (int)(imageBounds.width() * ratio);
imageBounds.bottom = imageBounds.top + (int)(imageBounds.height() * ratio);
}
return imageBounds;
}
});
}
})
The MarkdownRenderer class is a custom renderer for displaying Markdown content in an Android application. It utilizes the Markwon library, which is a powerful Markdown renderer for Android, to parse and render Markdown with additional features such as syntax highlighting, LaTeX support, image handling, and custom interactions.
Let's break down the key components and functionalities of the MarkdownRenderer class:
1. Class Structure and Dependencies
-
Context and Markwon Instances: The class holds a reference to the Android Context and an instance of Markwon, which is the primary engine for processing and rendering Markdown content.
-
Imports: The class imports various packages from the Markwon library and other Android components needed for rendering and interaction.
2. Inner Classes for Custom Spans
ClickToCopySpan
CopyIconSpan
3. Markwon Configuration
The constructor of the MarkdownRenderer class sets up the Markwon instance with various plugins and configurations:
Syntax Highlighting
- Uses
SyntaxHighlightPlugin with Prism4j for syntax highlighting in code blocks.
Custom Span Factories
- Configures
MarkwonSpansFactory to append both ClickToCopySpan and CopyIconSpan to FencedCodeBlock elements. This means every code block will have both the ability to be copied and display the copy notice.
LaTeX Support
Images and Inline Parsing
Linkify and Movement Methods
-
Incorporates LinkifyPlugin to automatically detect and convert URLs into clickable links.
-
Commented out TablePlugin and MovementMethodPlugin for table support, indicating potential instability or issues with these features.
Markdown Preprocessing
Image Size Configuration
-
Overrides the default image size resolver to limit the maximum display size of images to 120dp.
-
Scales down images proportionally if they exceed this maximum size to prevent them from occupying too much space in the view.
4. Rendering Method
-
render Method:
-
Checks if both textView and markdown are not null.
-
Uses markwon.setMarkdown(textView, markdown) to parse and render the Markdown content into the provided TextView.
-
Includes error handling to catch and print any exceptions during rendering.
5. Utility Classes and Methods
-
GlobalUtils:
- A utility class (not provided in the code) presumably contains methods for copying text to the clipboard (
copyToClipboard), showing toast messages (showToast), and converting dp to pixels (dpToPx).
Key Functionalities and Features
Potential Improvements and Considerations
Conclusion
The MarkdownRenderer class is a comprehensive solution for rendering Markdown content in an Android application, offering enhanced functionality beyond basic Markdown parsing. By integrating various plugins and customizations, it delivers a rich user experience with interactive code blocks, LaTeX rendering, and optimized image handling.
This implementation is well-suited for applications like note-taking apps, coding platforms, or educational tools where users interact with complex Markdown content. Ensuring that all dependencies are properly managed and considering the potential improvements can further enhance its effectiveness.