Using an alias resource
Using an alias resource
An alias resource is a resource that points to another resource. Alias resources live in res/values/ and,
by convention, are defined in a refs.xml file.
Your next job will be to have CrimeListActivity show a different layout file depending on whether
it is on a tablet or a phone. You do this the same way you show a different layout for landscape and
portrait: by using a resource qualifier.
Doing that with files in res/layout works, but it has some drawbacks. Each layout file has to contain
a complete copy of the layout you want to show. This can result in a lot of redundancy. If you wanted
an activity_masterdetail.xml layout file, you would have to copy all of activity_fragment.xml
into res/layout/activity_masterdetail.xml and all of activity_twopane.xml into res/layout-
sw600dp/activity_masterdetail.xml. (You will see what sw600dp does in a moment.)
Instead of doing that, you will use an alias resource. In this section, you will create an alias resource
that points to the activity_fragment.xml layout on phones and the activity_twopane.xml layout on
tablets.
In the project tool window, right-click the res/values directory and create a new values resource file.
Name the file refs.xml and check that the directory is values. It should have no qualifiers. Click OK.
Then add the item shown in Listing 17.3.
Listing 17.3 Creating a default alias resource value (res/values/refs.xml)
This resource’s value is a reference to the single-pane layout. It also has a resource ID:
R.layout.activity_masterdetail. Note that the alias’s type attribute is what determines the inner
class of the ID. Even though the alias itself is in res/values/, its ID is in R.layout.
You can now use this resource ID in place of R.layout.activity_fragment. Make that change in
CrimeListActivity.
Listing 17.4 Switching layout again (CrimeListActivity.java)
@Override
protected int getLayoutResId() {
return R.layout.activity_twopane;masterdetail;
}
Run CriminalIntent to confirm that your alias is working properly. CrimeListActivity should inflate
the single-pane layout again.