当我使用反射来获取方法setHomeActionContentDescription时,如下所示:

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


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

最佳答案

不幸的是,该方法在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或任何您想要的操作。

10-07 15:32