Serpentos Serpentos - 2 months ago 7
Android Question

How can I import android support library in a way where I can modify it?

I want to modify the ViewPager class itself in Android Studio. I currently have the support-v4 library as a library dependency, but I know that Android Studio does not allow to directly edit external libraries.

Attempt 1:
I tried copy-pasting ViewPager inside a java.android.support.v4.view package within my project. When I modified and tested it, it didn't seem to work as it was displaying ViewPager's standard functionality instead of the modified one.

Attempt 2: I tried to change its package name to com.example.view to differentiate it from the support library. It didn't work well as some of ViewPager's functionalities depend on its rightful package name and this caused some errors such as ClassCastException.

Attempt 3: I tried to put ViewPager in a newly-added module called "lib" in which I included in settings.gradle and added as a dependency for my "app" module. Didn't seem to work either.

What I haven't tried was getting rid of the support-v4 gradle dependency and instead copy-pasting the entire source code inside my project. This is a bit much and I'd prefer not to do this as I want to keep the support-v4 library up to date while only overriding the ViewPager class. (Also I'm not sure how to get the latest version of the source code. I hear they only open source each major API release.)

What can I do from here? Thanks in advance.

Answer

What can I do from here?

Re-do Attempt 2. Where needed, copy other classes (e.g., PagerAdapter) into your com.example.view package, and switch your app code to reference those classes. Basically, you are forking ViewPager, and that may require you to fork more than just that one class.

Note that other code that expects the real ViewPager, such as indicators, will not work with your fork and would themselves need to be forked.

You may wish to consider if your alterations could be handled via a simple subclass instead.

I know that Android Studio does not allow to directly edit external libraries

Moreover, as you note later in your question, if you modify the library, you would have to re-apply those modifications whenever that library changes.

Also I'm not sure how to get the latest version of the source code

The Java is on your hard drive, in the Android Repository. Look for the ...sources.jar file.