CodeView (Android)

repository·master·Indexed 21 days ago

https://github.com/kbiakov/codeview-android

A library for displaying code snippets with syntax highlighting in native Android views. It features customizable themes, fonts, and formatting, and supports an experimental CodeClassifier for automatic language recognition. The library allows for explicit language specification, custom code adapters via AbstractCodeAdapter for advanced UI like code diffs, and specialized views such as LineNoteView and LineDiffView.

Tokens
3.6K
Snippets
16
Records
16
Agent score
74%

What's inside CodeView (Android)

  1. Update existing CodeView options

    master

    When a CodeView is already initialized (via setOptions or setAdapter), calling setOptions or setAdapter again will 'flush' the current adapter. To update specific parameters without losing the current state, use updateOptions(...) or updateAdapter(...).

    // Update existing options without flushing the adapter
    codeView.getOptions()
        .withCode(R.string.listing_java)
        .withLanguage("java")
        .withTheme(ColorTheme.MONOKAI);
  2. Enable automatic language recognition

    master

    CodeView includes an experimental CodeClassifier module that uses a Naive Bayes classifier to detect the programming language of a code snippet. To improve performance and accuracy, initialize the classifier in your Application class so it can train on the library's language sets during app startup.

    // In your Application class
    CodeProcessor.init(this);
  3. Basic usage of CodeView

    master

    Add the CodeView to your XML layout and bind it in your Activity or Fragment. You can set code content either implicitly (allowing the library to attempt language detection) or explicitly (providing a language extension for faster processing).

    <!-- In your layout XML -->
    <io.github.kbiakov.codeview.CodeView
        android:id="@+id/code_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    // In your Activity/Fragment
    CodeView codeView = (CodeView) findViewById(R.id.code_view);
    
    // Option 1: Auto language recognition (slower)
    codeView.setCode(getString(R.string.listing_js));
    
    // Option 2: Explicit language extension (faster)
    codeView.setCode(getString(R.string.listing_py), "py");
  4. Install CodeView (Android) via JitPack

    master

    To use CodeView in your Android project, add the JitPack repository to your root build.gradle file and then add the library dependency.

    // In root build.gradle
    allprojects {
        repositories {
            ...
            maven { url "https://jitpack.io" }
        }
    }
    
    // In app build.gradle
    dependency {
        compile 'com.github.kbiakov:CodeView-Android:1.3.2'
    }
  5. Implement a Custom Code Adapter

    master

    To gain full control over how code lines are rendered (e.g., adding custom footers for diffs or metadata), extend AbstractCodeAdapter<T> where T is your custom model class. You must implement createFooter to return a view for your model entities.

    // 1. Define your model
    public class MyModel { ... }
    
    // 2. Extend AbstractCodeAdapter
    public class MyCodeAdapter extends AbstractCodeAdapter<MyModel> {
        public MyCodeAdapter(@NotNull Context context, @NotNull String content) {
            super(context, content, true, 10, context.getString(R.string.show_all), null);
        }
    
        @NotNull
        @Override
        public View createFooter(@NotNull Context context, @NotNull MyModel entity, boolean isFirst) {
            return /* your initialized view here */;
        }
    }
    
    // 3. Use the adapter
    final MyCodeAdapter adapter = new MyCodeAdapter(this, getString(R.string.listing_py));
    codeView.setAdapter(adapter);
    
    // 4. Add footer entities (e.g., for diffs)
    adapter.addFooterEntity(16, new MyModel(getString(R.string.py_addition_16), true));
  6. Customize Color Themes

    master

    You can use built-in themes like SOLARIZED_LIGHT or MONOKAI. You can also derive a new theme from an existing one or create a completely custom ColorThemeData from scratch.

    // Use a built-in theme
    codeView.getOptions().setTheme(ColorTheme.SOLARIZED_LIGHT);
    
    // Derive a theme from an existing one
    ColorThemeData myTheme = ColorTheme.SOLARIZED_LIGHT.theme()
        .withBgContent(android.R.color.black)
        .withNoteColor(android.R.color.white);
    codeView.getOptions().setTheme(myTheme);
    
    // Create from scratch
    ColorThemeData customTheme = new ColorThemeData(new SyntaxColors(...), ...);
    codeView.getOptions().setTheme(customTheme);
  7. Configure Fonts and Formatting

    master

    You can set the font using presets like Font.Consolas or provide your own Typeface. You can also manage the vertical spacing (format) using presets like Compact, ExtraCompact, or Medium, or by providing a custom Format object.

    // Set Font
    codeView.getOptions().withFont(Font.Consolas);
    
    // Set Format (Java)
    codeView.getOptions().withFont(Format.Default.getCompact());
    
    // Set Format (Kotlin)
    codeView.getOptions().withFont(Format.Compact)
  8. Initialize CodeView with Options

    master

    Instead of using setCode with default parameters, you can initialize a CodeView with a specific configuration using setOptions. This allows you to define the language, code content, and color theme upfront.

    codeView.setOptions(Options.Default.get(this)
        .withLanguage("python")
        .withCode(R.string.listing_py)
        .withTheme(ColorTheme.MONOKAI));
  9. Reference: Supported Language Extensions

    master

    When using setCode(content, extension), use one of the following supported extensions to enable syntax highlighting.

    C/C++/Objective-C: "c", "cc", "cpp", "cxx", "cyc", "m"
    C#: "cs"
    Java: "java"
    Bash: "bash", "bsh", "csh", "sh"
    Python: "cv", "py", "python"
    Perl: "perl", "pl", "pm"
    Ruby: "rb", "ruby"
    JavaScript: "javascript", "js"
    CoffeeScript: "coffee"
    Rust: "rc", "rs", "rust"
    Appollo: "apollo", "agc", "aea"
    Basic: "basic", "cbm"
    Clojure: "clj"
    Css: "css"
    Dart: "dart"
    Erlang: "erlang", "erl"
    Go: "go"
    Haskell: "hs"
    Lisp: "cl", "el", "lisp", "lsp", "scm", "ss", "rkt"
    Llvm: "llvm", "ll"
    Lua: "lua"
    Matlab: "matlab"
    ML: "fs", "ml"
    Mumps: "mumps"
    N: "n", "nemerle"
    Pascal: "pascal"
    R: "s", "R", "S", "Splus"
    Rd: "Rd"
    Scala: "scala"
    SQL: "sql"
    Tex: "latex", "tex"
    VB: "vb", "vbs"
    VHDL: "vhdl"
    Tcl: "tcl"
    Wiki: "wiki.meta"
    XQuery: "xq", "xquery"
    YAML: "yaml", "yml"
    Markdown: "md", "markdown"
    Formats: "json", "xml", "proto"
    Regex: "regex"
  10. Update CodeView options

    master

    You can modify the configuration of an existing CodeView using updateOptions. This method is useful for changing themes, fonts, or language settings on the fly.

    • updateOptions(options: Options): Replaces the current options with a new Options instance.
    • updateOptions(body: Options.() -> Unit): Provides a DSL-style way to modify the existing options using a lambda.
    // Using the DSL approach to update existing options
    codeView.updateOptions {
        // modify properties of Options here
    }
  11. Create a LineNoteView using the Factory method

    master

    The LineNoteView is a specialized TextView used to display notes or annotations on specific lines of code. Instead of manual instantiation, use the LineNoteView.create() factory method to ensure correct padding, text size, and styling.

    Parameters for create():

    • context: The Android Context.
    • text: The string content of the note.
    • isFirst: A boolean indicating if this is the first footer view. If true, a top padding is applied.
    • bgColor: The integer color value for the background.
    • textColor: The integer color value for the text.
    val noteView = LineNoteView.create(
        context = context,
        text = "Your note text here",
        isFirst = true,
        bgColor = Color.GRAY,
        textColor = Color.WHITE
    )
  12. Initialize CodeView with options or an adapter

    master

    To use CodeView, you must provide it with either an Options object or a specific AbstractCodeAdapter.

    • Use setOptions(options: Options) to initialize the view with a default CodeWithNotesAdapter configured with your settings.
    • Use setAdapter(adapter: AbstractCodeAdapter<*>) to provide your own custom adapter implementation.
    • If you call setCode() before initialization, the view will automatically call prepare(), which sets up a default CodeWithNotesAdapter with default options.
    // Option 1: Initialize with specific options
    val options = Options(context).apply { /* configure options */ }
    codeView.setOptions(options)
    
    // Option 2: Initialize with a custom adapter
    val myAdapter = MyCustomAdapter(context)
    codeView.setAdapter(myAdapter)