java.lang.NoSuchMethodException:setHomeActionContentDescription [int]?

时间:2014-12-02 10:22:55

标签: java android reflection nosuchmethoderror

当我使用反射来获取方法setHomeActionContentDescription时:

Method setHomeActionContentDescription = ActionBar.class.getDeclaredMethod(
    "setHomeActionContentDescription", Integer.TYPE);

我得到NoSuchMethodException: java.lang.NoSuchMethodException: setHomeActionContentDescription [int]

1 个答案:

答案 0 :(得分:1)

不幸的是,这种方法在API 18之前不可用。即使使用反射,该方法也不可用。如果要使用此方法,可以使用SherlockNavigationDrawer库中的解决方法:

            try {
                setHomeAsUpIndicator = ActionBar.class.getDeclaredMethod("setHomeAsUpIndicator",
                        Drawable.class);
                setHomeActionContentDescription = ActionBar.class.getDeclaredMethod(
                        "setHomeActionContentDescription", Integer.TYPE);

                // If we got the method we won't need the stuff below.
                return;
            } catch (NoSuchMethodException e) {
                // Oh well. We'll use the other mechanism below instead.
            }

            final View home = activity.findViewById(android.R.id.home);
            if (home == null) {
                // Action bar doesn't have a known configuration, an OEM messed with things.
                return;
            }

            final ViewGroup parent = (ViewGroup) home.getParent();
            final int childCount = parent.getChildCount();
            if (childCount != 2) {
                // No idea which one will be the right one, an OEM messed with things.
                return;
            }

            final View first = parent.getChildAt(0);
            final View second = parent.getChildAt(1);
            final View up = first.getId() == android.R.id.home ? second : first;

            if (up instanceof ImageView) {
                // Jackpot! (Probably...)
                upIndicatorView = (ImageView) up;
            }

来源:https://github.com/nicolasjafelle/SherlockNavigationDrawer/blob/master/SherlockNavigationDrawer/src/com/sherlock/navigationdrawer/compat/SherlockActionBarDrawerToggleHoneycomb.java#L97

如您所见,如果无法访问方法,他会尝试直接获取ImageView。当你拥有它时,你可以直接做一个setContentDescription或任何你想要的。