Where to put PNG files and how to refer to them from ImageView in XML layout?

Alexander Farber picture Alexander Farber · Oct 21, 2014 · Viewed 9.4k times · Source

After reading 2 books on Android programming, I am trying to port an iOS Word game app:

word game screenshot

I would like to have 2 classes inheriting from View - SmallTile.java and BigTile.java.

Both classes should be composed of an ImageView (id: "image") and 2 TextViews (ids: "letter" and "value").

The difference between them is that BigTile will be draggable and its "image" has a shadow.

I have put the graphical assets into the directory res/drawable-mdpi and I am trying to refer to them from the layout files res/layout/small_tile.xml and res/layout/big_tile.xml as:

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/image"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/small_tile.png" >
</ImageView>

But I get the error

No resource found that matches the given name (at 'src' with value '@drawable/small_tile.png')

as you can see in the Eclipse-screenshot (here fullscreen):

eclipse screenshot

I have tried other paths for my assets as well - for example res/drawables and src/assets.

Also another question: how to load the layout files from a View?

There is only an ImageView in the res/layout/small_tile.xml right now, but I'd like to add the two TextViews there too (for the letter and its numerical value) - and then load it from the SmallTile.java.

From the programming books I know how to load a layout from Activity or Fragment - call setContentView(R.layout.activity_main); in onCreate - but where and what to call in a View class?

Answer

Bryan Herbst picture Bryan Herbst · Oct 21, 2014

When referencing Drawables, you only refer to them by their file name. You should omit the extension.

For example, the ImageView you posted should look like this in XML:

<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/image"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/small_tile" >

Note the change from android:src="@drawable/small_tile.png" to android:src="@drawable/small_tile"

To use your custom layout with your View, you will want to create a LayoutInflater and call inflate(R.id.my_layout, this);. For example:

public SmallTile(Context context) {
    LayoutInflater inflater = LayoutInflater.from(context);
    inflater.inflate(R.layout.my_view_layout, this);
}