Android SharedPreferences Tutorial and Example

Build an Android Code Editor with Syntax Highlighting

A code editor inside an Android app can be a useful learning project because it combines text input, file handling, scrolling, menus, and visual styling. A simple version might edit Kotlin, JavaScript, XML, or JSON files, while a more advanced app can provide line numbers, search, indentation, and basic error markers.

The most reliable approach is to separate the editor into small responsibilities. One component displays and edits text, another identifies language tokens, and a third manages files and user actions. This structure keeps the project approachable for beginners while leaving room for features that experienced Android developers expect.

Choose An Editor Architecture

Android’s standard EditText is suitable for a basic editor, especially when the goal is to teach text input and document storage. For larger files, however, continuous syntax processing can make typing feel slow. A custom view or a specialised text component gives you greater control over drawing, cursor behaviour, selection, and scrolling.

A practical design uses a document model containing the current text, file name, language mode, and unsaved state. The editor view observes that model, while a syntax analyser produces coloured spans. File operations should run away from the main thread so opening a sizeable file does not freeze the interface.

Kotlin makes this separation straightforward. A ViewModel can retain the document during screen rotation, and StateFlow can expose changes to the activity or fragment. Store the active file’s location rather than placing the whole document in SharedPreferences; preferences are intended for small settings such as the selected theme or font size.

Create The Editing Surface

Begin with a vertically scrolling container holding a custom editor view. The view can draw the text, line numbers, and background, while an invisible or transparent input connection receives keyboard events. For a first project, a styled EditText is simpler: attach a TextWatcher, apply spans, and add a horizontal scroll container if long lines must remain visible.

Line numbers should be calculated from newline characters and drawn using a fixed-width typeface. Keep the gutter separate from the editable text so selecting or copying code does not include the numbers. Set sensible padding and minimum line height, as cramped text becomes difficult to read on smaller phones used on Sydney trains or during a quick commute.

Use a monospace font such as monospace or a bundled developer-friendly typeface. Respect the user’s system font scaling, offer light and dark themes, and ensure the text and gutter have adequate contrast. Large tap targets and a visible cursor matter when the app is used outdoors in bright Melbourne sunlight.

Tokenise Text Efficiently

Syntax highlighting works by identifying lexical tokens such as keywords, strings, comments, numbers, and annotations. A small regular-expression scanner can support a demonstration language, but regular expressions alone become unreliable when strings contain comment markers or when nested structures appear. A stateful scanner that moves through the document character by character is easier to extend.

For example, the scanner can emit a token type and range:

data class Token(
    val start: Int,
    val end: Int,
    val type: TokenType
)

The renderer then maps each type to a colour. Apply ForegroundColorSpan objects to a Spannable for a simple implementation. Avoid rebuilding every span after each keystroke in a large document; first rescan the changed line and nearby lines, then replace only the affected range.

Use a debounce interval of roughly 100–200 milliseconds before starting analysis. This prevents the parser from competing with rapid typing. A background coroutine can process the text snapshot, while the UI thread applies the resulting spans only if the snapshot is still current. This check prevents older parsing results from overwriting newer text.

Add Files, Actions, And Safety

An editor becomes useful when it can create, open, save, and rename documents. Android’s Storage Access Framework is a strong choice because it lets users select files through the system picker without requiring broad storage access. Use ACTION_OPEN_DOCUMENT for opening and ACTION_CREATE_DOCUMENT for saving a new file.

Keep encoding and file type visible in the interface. UTF-8 should be the default, while a failed read should produce a clear message rather than a blank editor. Save a temporary copy before replacing an existing document, then restore it if a write fails. This protects work when a device loses power or an app is closed unexpectedly.

Privacy deserves attention in an Australian release. If documents are processed entirely on the phone, state that clearly and avoid collecting file contents for analytics. If synchronisation or crash reporting sends code to a server, explain the practice in the privacy policy and consider the Australian Privacy Act 1988 and its Australian Privacy Principles. The Google Play market also rewards clear data-safety disclosures and transparent permissions.

A command bar can provide save, undo, redo, find, replace, and language selection. Reusing patterns from a playlist architecture example can help when modelling ordered items, current selections, and state changes, even though the editor’s content model is different.

Compare Rendering Options

Choose the rendering strategy according to the editor’s intended size and complexity. A styled EditText is excellent for a tutorial or small configuration editor. A custom canvas can deliver precise line numbers and minimap features, but it requires careful work for cursor placement, accessibility, selection handles, and IME integration.

Test with Kotlin source, XML layouts, JSON, and deliberately malformed text. Check long lines, empty files, pasted blocks, emoji, mixed line endings, and files containing thousands of lines. Test on a current Pixel device and an older handset commonly used in the Australian second-hand market, where limited memory can reveal inefficient span creation.

Approach Strengths Limitations Suitable Use
Styled EditText Fast to build, native selection, strong accessibility Can slow down with many spans Beginner projects and small files
Custom View Full control over drawing and gutters Complex input and selection handling Large documents and specialised layouts
Recycler-based lines Efficient for very large files Harder cursor and scrolling logic Advanced editors
Web-based editor Mature highlighting libraries Extra memory and bridge complexity Rich multi-language tooling

Finish with focused instrumentation tests for loading, saving, highlighting, and rotation. Measure typing latency rather than relying on appearance alone. A clean architecture, incremental tokenisation, and careful storage handling will produce an Android code editor that feels responsive while remaining understandable enough for continued tutorial development.