1

I have an animation using ViewCompat.animate() on one of my Screen that uses FrameLayout and it looks fine on the test phone. But of course, once running on the test tablet (Nexus 7 2013), the animation isn't the same.

So I'm searching a way to get the same displayed translation Y, on different screen sizes without using different dimens resource files. Surely there is a way to calculate it at Run time and sort it out by itself.

I tried: float px = -182 * (getResources().getDisplayMetrics().densityDpi / 160f); But the distance traveled by the view on the 2 screens are not the same.

Saw this post but didn't provide the solution: android animation in different screen sizes

Anyone has an idea?

Cheers

Community
  • 1
  • 1
Andy Strife
  • 729
  • 1
  • 8
  • 27
  • Could you make a log of the value "getResources().getDisplayMetrics().densityDpi" ? and check it on both devices. In Android Developer website, it still saying: densityDpi [The screen density expressed as dots-per-inch. May be either DENSITY_LOW, DENSITY_MEDIUM, or DENSITY_HIGH.]. I am not sure if it will retrun DENSITY_XHIGH, DENSITY_XXHIGH or not. – i_A_mok Oct 01 '16 at 05:44
  • It gives the value of the category it fits in, such as 360 or 480 – Andy Strife Oct 01 '16 at 18:45

2 Answers2

2

So here is what I tried, getting the height dpi of the device and use it to convert a dp value (182) into pixels.

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
float yDpi = displayMetrics.ydpi;
float px = 182 * (yDpi / 160);

While the result of the px value is different with every devices, the translation still doesn't travel the same distance on different screens

So I sorted it out doing this:

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

float translationY = displayMetrics.heightPixels * 0.40f;

Got the Screen Height and used to calculate the distance to travel equal to 40% of the device screen height. So now, whatever the used device, the animation is the same and travels the same distance. Also, the float value used can be very precise. I used 0.40f but you can do something like 0.398f

Andy Strife
  • 729
  • 1
  • 8
  • 27
0

In order to avoid any extra unnecessary math it is easier to get the metrics from the view already displayed on the screen. The only thing needed is to have a post in onCreate, in case of activity. In case of fragment you can simply to things directly in onViewCreated without any post

View settingsView = findViewById(R.id.settings_layout);
View youtubeView = findViewById(R.id.youtubeLink);
settingsView.post(new Runnable() {
    @Override
    public void run() {
        //metrics already calculated
        settingsView.animate().translationX(youtubeView.getWidth());
    }
});
Duna
  • 1,564
  • 1
  • 16
  • 36