有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓 java。lang.NoSuchMethodException:setHomeActionContentDescription[int]?

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

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

我没有得到任何异常: java.lang.NoSuchMethodException: setHomeActionContentDescription [int]


共 (1) 个答案

  1. # 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或者任何你想做的事情