Search code examples
androidfragmenttransactionobjectanimator

Setting animator xml values dynamically


I am developing a turn based game, and there are 2 game boards, and when i want to switch between the 2 gameboards, i use a sliding animation. But here comes the problem. I have 4 animator xml files, in-right, out-right, in-left, out-left. here is one of them:

<objectAnimator
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:propertyName="x"
    android:valueFrom="1000"
    android:valueTo="0"
    android:valueType="floatType" />

The sliding is working, but i test this game on an emulator with 1280px height (and the game is running in landscape mode), at the end of the slide, there is a 280px wide part, that isn't sliding, just hiding at the end of the sliding animation. When i set the valuefrom value to 2000, it is better, because the two board are not fading the other, but in this case there is a 720 px wide black area.

Do you know, how can i set these values dynamically based on the actual screen size? Thanks.


Solution

  • Use the factoring methods of ObjectAnimator.

    Example:

    ObjectAnimator anim = ObjectAnimator.ofFloat(targetObject, "x", 0.f, 1000.f);
    anim.setDuration(300);
    anim.start();
    

    You can get the metrics of the display or size of the Views programmatically with code like

    getWindowManager().getDefaultDisplay().getWidth();
    
    View view = ...;
    view.getHeight();
    

    See: