When I was writing a control.
There is a classsubViewPager
that inheritsViewPager
. I need to use thegetCurrentItem()
method of thisViewPager
in another place. , which means to obtain a certain coordinate of this control.
But because myViewPager
is for special effects, the coordinates returned by itsgetCurrentItem()
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, hisgetCurrentItem()
method should return a number like40280
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 usednew 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 causeGC
, 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 ofsubViewPager
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?
Isn’t it enough for subViewPager to override getCurrentItem()? .
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()