As part of an app I'm working on, I'm attempting to obtain a reference to the ActionBar's container view. I used the answer from this question, and it's working nicely for me as long as the Android device in question is running API level 11 or up. However, the app needs to work as far back as API level 9 (the target API level is 19), and Gingerbread devices are giving me problems. I was originally using Sherlock for the project, but recently made the switch over to the v7 compat library instead. I can see and interact with the action bar in normal ways on Gingerbread devices (buttons work, etc.), but it fails when I attempt to get the container. The code I'm using is this (note - it's running inside a subclass of ActionBarActivity):

private FrameLayout getActionBarContainer() {
    FrameLayout result = null;

    int resId = getResources().getIdentifier("action_bar_container", "id", "android");
    try {
        result = (FrameLayout)getWindow().getDecorView().findViewById(resId);
    }
    catch (Exception e) {
        // If we get an exception, just eat it
    }

    return result;
}

To answer a few questions before they get asked:

  1. resId resolves to a proper ID value on v11 devices and up, but resolves to 0 on pre-v11 devices.
  2. The code that uses this has proper checks to handle a null result, which is why I'm just eating the exceptions. The try/catch block is mostly just there in case, by some freak occurrence, a ClassCastException manages to get thrown (which it never should, since the container is a subclass of FrameLayout).
  3. I've checked and re-checked my imports; all of my ActionBar references (and all things related, like the ActionBarActivity superclass I'm extending) are the v7 compat library versions, not the standard library versions.
  4. The action_bar_container ID should exist within the v7 compat library, if this is any indication.

I'm about out of ideas at this point. Is there something simple I'm missing? Any suggestions will be appreciated, and if you need more context/clarification, let me know.

有帮助吗?

解决方案

I think your error is on the last parameter of

int resId = getResources().getIdentifier("action_bar_container", "id", "android");

For api level <11 the package should be your application's package and not the plataform's package "android"

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top