I want to make Interpolator selectable from drop-down list in View.animation on Android

Asked 2 years ago, Updated 2 years ago, 74 views

A total of 9 Interpolators have been added to Spinner.
I want to be able to change every time I press the setInterpolator button depending on the item selected.
For example, if you select AnticipateInterpolator in Spinner and tap the Move button, AnticipateInterpolator will be added to the normal movement animation and displayed.
I'd like to do it like this
I want to set up Interpolator for each effect
Enter a description of the image here

I'm thinking about judging the spinner items by the if statement, one by one

 if (value obtained from spinner == OvershootInterpolator) {
    trans.setInterpolator (new OvershootInterpolator());
else if (value obtained from spinner == AnticipateInterpolator) {
    trans.setInterpolator(newAnticipateInterpolator());

All I can think of is writing, but it will be difficult if the number increases.
If there is a good way, please let me know

android

2022-09-30 20:55

1 Answers

I think it's better to keep it in the Map.

Simply prepare the Map<String,Interpolator>, which will generate useless Interpolator, and I will try to use the reflection because I have no tricks.

We do not consider Animation that is only available in certain versions of SDK or defined resources, but

final static Map<String, Class<?extends Interpolator>>easingMap;
static {
    Map<String, Class<?extends Interpolator>>tmpMap=new HashMap<>();
    tmpMap.put("OvershootInterpolator", android.view.animation.OvershootInterpolator.class);
    makingMap=Collections.unmodifiableMap(tmpMap);
}

Define these Map and

Animation anim=null;
try{
    anim=newTranslateAnimation(0,10,300,20);
    anim.setDuration(500);
    anim.setInterpolator(easingMap.get("OvershootInterpolator").getConstructor().newInstance());
} catch(Exceptione){
    // InstantiationException, IllegalAccessException, InvocationTargetException,
    // NoSuchMethodException needs to be handled, but it is an example, so it is a Pokémon exception handling.
    e.printStackTrace();
}

if(anim!=null){
    imageView.startAnimation(anim);
}

You can use getConstructor().newInstance() to dynamically generate Interpolator.


2022-09-30 20:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.