When I am developing an Android Application ,I want to use a method of higther API in lower android version. How to do it?

StackOverflow https://stackoverflow.com/questions/14191258

Question

When I am developing an Android Application ,I want to use a method of higther API in lower android version?? the following is a method of ListView

public void smoothScrollToPosition(int position)  Since API Level 8,

but I want to use this method in in a lower android version ,for example ,API 5 how to do it ???? thank you

Was it helpful?

Solution

Basically you can't do it. But, you can use it in upper version and provide some backwards compatibility in your code for older versions :

@TargetApi(Build.VERSION_CODES.FROYO)
private void allowSmoothScrollIfSupported() {
    if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO ) {
        list.smoothScrollToPosition(position)
    } else {
        list.scrollToPosition(position)
    }
}

This method will only be executed on API versions 8 and above, and will not crash below : it will fallback on an old API (scrollToPosition).

and in your AndroidManifest.xml you can indicate that your target the newest api but support all of them from 5 and up :

 <uses-sdk
        android:minSdkVersion="5"
        android:targetSdkVersion="17" />

OTHER TIPS

Alternatively to the @snicolas's soltution, you can use reflection:

    try {       
        Method smoothScrollToPositionMethod = ListView.class.getMethod("smoothScrollToPosition", int.class);
        smoothScrollToPositionMethod.invoke(list, position);
    } catch (NoSuchMethodException e) {
         list.scrollToPosition(position)
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top