When I was writing a control.
There is a class subViewPager
that inherits ViewPager
. I need to use the getCurrentItem()
method of this ViewPager
in another place. , which means to obtain a certain coordinate of this control.
But because my ViewPager
is for special effects, the coordinates returned by its getCurrentItem()
may exceed the length of my data collectionsize
,
For example, the length of my data collection is
size = 1024
andgetCurrentItem()
returns40280
So when I call him actively, I hope that he can return to me the result of coordinates %=size: 4028 24
.
At the same time, his getCurrentItem()
method should return a number like 40280
when called by the system.
My original approach was to write a special method to obtain the result after %=size
. Force it when you need to get this parameter.
Later I changed a bit and used new Exception().getStackTrace();
to obtain the call stack information to determine whether the method was called by the specified class. This eliminates the need to force and write a subclass-specific method.
But this approach will generate a lot of garbage memory and frequently cause GC
, so consider using the first method to deal with it.
But forced transfer is always a bit unpleasant, and it feels like there is no reusability. (Although it is because of the bad code... and the reusability of subViewPager
is also reduced by doing this) So I want to ask if there is any way to make the same method be called in different classes. Can you perform different operations gracefully?
欧阳克2017-07-03 11:44:06
I have seen implementation solutions of similar libraries. If the business logic returned by your internal and external calls of this method is not consistent, it is recommended to define an additional method...such as getCurrentRealItem()