开发者

Trouble using reflection with setOverScrollMode

开发者 https://www.devze.com 2023-03-20 08:27 出处:网络
I want to be able to turn off overscroll (the glowing effect when reaching the top or bottom of a page in 2.3+) however I also want my code to run in older versions of android that don\'t even have ov

I want to be able to turn off overscroll (the glowing effect when reaching the top or bottom of a page in 2.3+) however I also want my code to run in older versions of android that don't even have overscroll functionality. As per the documentation here: Android Backwards Compatibility I am using reflection in my custom webview class to call setOverScrollMode however everytime I call this on a device running 2.3.4, I get a NoSuchMethodException. Any idea why I can't retrieve this method?

Strangely, if I just call setOverScrollMode without any ref开发者_StackOverflow社区lection, it works, so the method is definitely there.

public class MyWebView extends WebView{

    public void compatibilitySetOverScroll(){
    try {
        Method mWebview_SetOverScroll = WebView.class.getMethod("setOverScrollMode", new Class[] { Integer.class } );
        /* success, this is a 2.3+ */
        if (mWebview_SetOverScroll != null) {
            try {
                mWebview_SetOverScroll.invoke(this, 2);
            } catch (InvocationTargetException ite) {       
                throw new RuntimeException(ite.getCause());
            } catch (IllegalAccessException ie) {
                System.err.println("unexpected " + ie);
            }               
        }
    } catch (NoSuchMethodException nsme) {
        /* failure, must be older device */
    }        
}
}


Try Integer.TYPE instead of Integer.class


More correct version:

public static void disableOverscroll(View view) {
    Class<?> viewCls = view.getClass();
    try {
        Method m = viewCls.getMethod("setOverScrollMode",
                new Class[] { int.class });
        int OVER_SCROLL_NEVER = (Integer) viewCls.getField(
                "OVER_SCROLL_NEVER").get(view);
        m.invoke(view, OVER_SCROLL_NEVER);
    } catch (Exception e) {
        // swallow
    }
}


another way :

try
{
    Class<?> myTarget = Class.forName("android.widget.HorizontalScrollView");
    Method myMethod = myTarget.getDeclaredMethod("setOverScrollMode", Integer.TYPE);
    myMethod.invoke(scrollView, 2);
}
catch (Exception e)
{
    e.printStackTrace();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消