Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 104 ยท Getting Started

Android Resources: res, raw, assets, Drawables and Densities

Learn where files go in an Android project: res versus assets versus raw, drawable densities, vector assets and SVG import, shape and selector drawables, fonts, local HTML and Android Studio tips.

Every real app contains more than code: images, icons, colors, strings, fonts, sounds, a local HTML page, a JSON file. Android gives you three places for such files, and putting a file in the wrong one is a common beginner problem. This lesson explains how to choose between res/, res/raw/ and assets/, how screen densities decide which image is loaded, how to import vector images, how to write drawables in XML, and a few Android Studio tricks for plugins, emulators and a faster IDE.

For the project layout in general see Project structure and for the string, color and theme resources see Manifest and resources. Android Studio and the resource compiler cannot run on this site, so Android snippets are read-only and the TryIts model the lookup rules in plain Kotlin.

Three folders, three behaviors

Folder How you reach files Gets an ID in R? Typical content
res/drawable, res/layout, res/values, ... Resource IDs, R.drawable.logo Yes Images, layouts, strings, colors, themes
res/raw R.raw.name, openRawResource(...) Yes Audio and video played by MediaPlayer, small data files
assets A path string through AssetManager No Files you want exactly as they are: HTML, JSON, fonts, databases, game data

The key differences:

  • res/raw files keep their bytes and are addressed by ID (R.raw.chime), but the file name must be a valid resource name: lowercase letters, digits and underscores only, no spaces, no capitals, and it cannot start with a digit. Raw does not allow subdirectories. You open a file with resources.openRawResource(R.raw.data) or play it with MediaPlayer.create(this, R.raw.chime).
  • assets is a real folder tree: any file names, any nested directories. There is no R constant, you ask the AssetManager for a path, and you can list files at run time with assets.list("levels"). Because they have no IDs, assets cannot use resource qualifiers such as -night or -hdpi.
  • Everything under res/ can use qualifiers (language, density, orientation, night mode), and the build tools may process the files (compress PNGs, convert vectors). Raw and assets are copied unchanged.
Kotlin
// read-only example: read a JSON file from assets and a text file from raw
val levels: String = assets.open("levels/level1.json").bufferedReader().use { it.readText() }

val names: List<String> = assets.list("levels")?.toList().orEmpty()   // ["level1.json", "level2.json"]

val welcome: String = resources.openRawResource(R.raw.welcome).bufferedReader().use { it.readText() }

Rule of thumb: need an ID, a qualifier or tool processing: res. Need media that MediaPlayer plays by ID: res/raw. Need arbitrary names, folders or run-time listing: assets.

Kotlin Is this a valid res/raw file name?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Note that two files with the same base name and different extensions (beep.mp3 and beep.ogg in the same raw folder) collide on one ID. That is also why the error is "duplicate resources", not a missing-file error.

Playing audio and loading a local HTML page

Audio you ship with the app goes in res/raw:

Kotlin
// read-only example: play a bundled sound
val player = MediaPlayer.create(this, R.raw.chime)
player.start()
player.setOnCompletionListener { it.release() }     // always release the player

A local HTML file belongs in assets, because HTML pages reference each other by relative paths, which would break if names were turned into resource IDs. A WebView loads it with a special URL scheme (see WebView and search):

Kotlin
// read-only example: show assets/help/index.html in a WebView
binding.webView.loadUrl("file:///android_asset/help/index.html")

Screen densities and the drawable folders

Phones have very different pixel densities. A 48 dp button is about 48 pixels on a low-density screen and 192 pixels on a very dense one. To keep bitmaps sharp without scaling too much, you can supply the same image at several sizes in density-qualified drawable folders, and Android picks the closest one.

Folder Density bucket dpi Scale A 48 dp icon is
drawable-ldpi low ~120 0.75x 36 px
drawable-mdpi medium (baseline) ~160 1x 48 px
drawable-hdpi high ~240 1.5x 72 px
drawable-xhdpi extra high ~320 2x 96 px
drawable-xxhdpi extra extra high ~480 3x 144 px
drawable-xxxhdpi extra extra extra high ~640 4x 192 px
drawable-nodpi never scaled - - as is

ldpi is almost extinct, so you can usually skip it. A file that must not be scaled (a bitmap whose pixel size matters) goes in drawable-nodpi. Design at the baseline (mdpi) size, then export multiples: for a 48 dp icon, 48, 72, 96, 144 and 192 pixels. If a density is missing, Android scales the nearest one, preferring to scale down from a larger image because it looks better than scaling up.

The matching in the framework is more detailed than this, but the idea is easy to model:

Kotlin Choosing the drawable bucket

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Because shipping five copies of every image bloats the APK, modern projects prefer vector drawables for icons and simple illustrations.

Vector drawables and importing SVG

A VectorDrawable is an XML description of paths. It scales to any density with no loss, so one small file replaces five PNGs. Use Vector Asset Studio in Android Studio: right-click res, choose New, Vector Asset, then either pick a Material icon or Local file to import an SVG (or a PSD, which must be converted to SVG first). Choose the name (resource naming rules apply, for example ic_freesample), size and opacity, and Studio writes res/drawable/ic_freesample.xml.

XML
<!-- read-only example: a vector drawable -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="?attr/colorControlNormal">
    <path
        android:fillColor="@android:color/white"
        android:pathData="M12,2L2,22h20L12,2z" />
</vector>

Not every SVG feature converts (filters and some gradients do not), so check the preview and simplify the SVG if the importer reports problems. Photos should stay raster (WebP is the preferred format; Studio converts PNGs with Convert to WebP), and app icons use adaptive icon XML with foreground and background layers.

Drawable resource XML

A drawable does not have to be an image file. res/drawable can hold XML that Android draws:

XML
<!-- read-only example: res/drawable/button_bg.xml, a rounded button -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#0F9D58" />
    <corners android:radius="12dp" />
    <stroke android:width="1dp" android:color="#0B7A45" />
</shape>
XML
<!-- read-only example: res/drawable/button_state.xml, color depends on state -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/button_pressed" />
    <item android:state_enabled="false" android:drawable="@drawable/button_disabled" />
    <item android:drawable="@drawable/button_bg" />
</selector>

Use them with android:background="@drawable/button_bg" in XML or ContextCompat.getDrawable(context, R.drawable.button_bg) in code. The root tags you will meet are shape, selector, layer-list (stacked layers), ripple (touch feedback; use ?attr/selectableItemBackground for the standard one), vector and animated-vector. In Compose you rarely need them: painterResource(R.drawable.ic_x) shows vector and bitmap resources, and shapes and colors are modifiers (Modifiers, Text, images and icons).

Custom fonts

Put font files (.ttf, .otf) into res/font/ (names follow the same lowercase rules), then reference @font/lato_regular in android:fontFamily. A font family XML in res/font groups regular, bold and italic files so textStyle works. You can also use downloadable fonts from Google Fonts so the font is not bundled. In Compose: FontFamily(Font(R.font.lato_regular)). See Material 3 theming for setting the app-wide typography.

Android Studio housekeeping

  • New classes and interfaces: right-click a package, New, Kotlin Class/File, then choose Class, Interface, Enum, Object or Sealed class; the dialog creates the file with the right package line.
  • Adding a JAR: put it in app/libs, and declare implementation(files("libs/mylib.jar")). Prefer a Maven dependency whenever one exists, because it also brings transitive dependencies.
  • Plugins: Settings, Plugins lists the Marketplace and installed plugins; enable, disable or update them, then restart the IDE. Too many plugins slow the IDE.
  • A faster IDE: give Studio more memory (Help, Change Memory Settings), enable the Gradle configuration cache and parallel builds in gradle.properties, exclude large irrelevant folders, and disable plugins you do not use (Gradle for Android).
  • Other emulators: besides the built-in Android Emulator (Android Studio setup), third-party emulators such as Genymotion exist; they plug into Studio through their own plugin and run Android in a virtual machine. A real device over USB or Wi-Fi is still the most reliable test.

Common mistakes

  • Putting a capitalized or spaced file name into res or res/raw: the build fails with "invalid file name".
  • Looking for an ID for an asset file. Assets have no R constants.
  • Shipping only an xxxhdpi image for everything, which wastes memory on small screens, or only mdpi, which looks blurry on dense screens.
  • Using large PNGs where a vector would do.
  • Forgetting release() on a MediaPlayer.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which folder lets you list files at run time with AssetManager and keep arbitrary folder structure?

    assets is a plain file tree reached by path strings; res/raw files are addressed by R.raw IDs and cannot use subfolders.
  2. 2. Which file name is valid in res/raw?

    Resource names allow lowercase letters, digits and underscores, and must not start with a digit.
  3. 3. How many pixels is a 48 dp icon on an xhdpi (320 dpi) screen?

    xhdpi is 2x the baseline, so 48 dp becomes 96 px.
  4. 4. Why prefer a vector drawable for a simple icon?

    Vectors describe shapes, so they stay sharp at any size and replace several PNG copies.

Summary

  • res gives IDs, qualifiers and tool processing; res/raw keeps bytes under an ID with strict names; assets is a free file tree reached by path.
  • Density buckets (mdpi 1x to xxxhdpi 4x) let Android choose the sharpest image; nodpi stops scaling.
  • Vector Asset Studio turns SVG into XML vectors; XML drawables (shape, selector, layer-list, ripple) replace many images.
  • Fonts live in res/font; local HTML goes in assets and opens with file:///android_asset/.
  • Keep Studio fast with enough memory, few plugins and Gradle caching.

Next: Android interview questions or continue with the Activities lesson.