简体   繁体   中英

Display markdown content in Jetpack compose

Currently there's no jetpack compose library for showing md content.

# Header
## H2

` code `
```dsd```
...

How can I make a composable function that can display markdown content?

You can use https://github.com/halilozercan/compose-richtext library. It has a commonmark module that renders markdown content according to commonmark spec.

Full documentation is available at https://halilibo.com/compose-richtext/richtext-commonmark/

An example of usage of this library:

RichText(
  modifier = Modifier.padding(16.dp)
) {
  Markdown(
    """
    # Demo

    Emphasis, aka italics, with *asterisks* or _underscores_. Strong emphasis, aka bold, with **asterisks** or __underscores__. Combined emphasis with **asterisks and _underscores_**. [Links with two blocks, text in square-brackets, destination is in parentheses.](https://www.example.com). Inline `code` has `back-ticks around` it.

    1. First ordered list item
    2. Another item
        * Unordered sub-list.
    3. And another item.
        You can have properly indented paragraphs within list items. Notice the blank line above, and the leading spaces (at least one, but we'll use three here to also align the raw Markdown).

    * Unordered list can use asterisks
    - Or minuses
    + Or pluses
    ---

    ```javascript
    var s = "code blocks use monospace font";
    alert(s);
    ```

    Markdown | Table | Extension
    --- | --- | ---
    *renders* | `beautiful images` | ![random image](https://picsum.photos/seed/picsum/400/400 "Text 1")
    1 | 2 | 3

    > Blockquotes are very handy in email to emulate reply text.
    > This line is part of the same quote.
    """.trimIndent()
  )
}

Currently (Oct, 2020), there are no available libraries to display markdown files or contents for Jetpack-compose .

However, It is possible to use an older library to display markdown and port it to a Composable

Using the mukeshsolanki's MarkdownView-Android :

  1. Create a composable:
@Composable
fun MarkdownText(
    content: String,
    modifier: Modifier = Modifier
) {
    Box(modifier = modifier.padding(2.dp)) {
        AndroidView(viewBlock = ::MarkdownView, modifier = modifier) {
            it.setMarkDownText(content)
        }
    }
}
  1. Use it in your composables
MarkdownText(
    content = """
    # Header
    ## H2

    ` code `
    ```dsd```
    """.trimIndent(),
    modifier = Modifier.fillMaxSize()
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM