tags:

views:

226

answers:

2

Hi everyone,

i wrote a View class based on ViewSwitcher and now I want to write helper classes for the view like known form the ListView: ListAdapter, ListActivity and so on..

Regarding the activity class I ran into a problem. The ListActivity forces you to add a ListView to your activity with a fixed id: @id/android:list. In my base activity class i want to archive the same, forcing a special id so that my helper classes can access the view object.

As I'm writing a general lib that could be used in various projects I can't use R.id.foobar to get the view as there's no R class. The specific project will an own R.java.

So I peeked at the source code of ListActivity and found:

View emptyView = findViewById(com.android.internal.R.id.empty);
mList = (ListView)findViewById(com.android.internal.R.id.list);
if (mList == null) {
    throw new RuntimeException(
        "Your content must have a ListView whose id attribute is " +
        "'android.R.id.list'");
}

Ok, I could write my on R class, put it directly into my package and try to access it in the same way but I've no clue what value the id should have or need?

Also I couldn't find any R class at android_frameworks_base/core/java/com/android/internal

And even if this problem is solved: How can the user of my lib access "my id" from his layout XML?

Thanks for your help! :)

A: 

I do not think this is safe, as Android has not supplied reusable widget authors with an ID range to use for your desired purpose.

Instead, do one of the following:

  1. Have the reuser of your widget pass in the appropriate ID.
  2. Use Resources#getIdentifier() to look up an ID in the R.* "namespace" given the string form of the name. If you go this route, be sure to cache this result, as it is a bit expensive to look up, apparently.
CommonsWare
Thanks! Resources#getIdentifier() is a good way to work around this problem :)
pocmo
A: 

If you're creating a library APK that other applications can use, then consumers of this library cannot refer to its resource IDs in XML layouts.

When an Android application is started, it loads in and caches resource information from the application APK (resources.arsc), plus the system resources (i.e. those in android.R). Your application, running in a separate process and as a different user ID, cannot directly read the resources from other APKs.

However, if you're just using the library for your own purposes, you should be able to get a greater level of access between your APKs by signing them with the same key, or specifying the same process ID in your manifest.

Christopher