0

I am trying to move a button via Script. Here is what it looks like:

   Handler handler2 = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            float y = chatButtonOne.getY();
            float yB = 40;
            float pxs = yB * getResources().getDisplayMetrics().density;
            chatButtonOne.setY(y - pxs);
            chatButtonOne2.setVisibility(View.VISIBLE);
        }

    }, 2000);

Now this (y - 40) is problematic in terms of different device sizes, so i am trying to use dp instead. Does anybody know how to do that?

Edit: This one here did the trick, i updated the original script i posted:

stackoverflow.com/a/14921982/1987425

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
griesgram
  • 71
  • 6

2 Answers2

1

You need to calculate the pixels to dp. You can achieve that with this:

public static int pixelToDps(Context context, int desiredDps) {
    final float scale = context.getResources().getDisplayMetrics().density; //get device density
    int calculatedPixels = (int) (desiredDps * scale + 0.5f);  //The +0.5 rounds up to the nearest whole number if necessary. When converted to integer, everything after the decimal is simply cut off. The +0.5 ensures that the most "correct" integer is returned
    return calculatedPixels;
}

See also here: https://stackoverflow.com/a/6656774/8490899

hannojg
  • 983
  • 8
  • 28
0

You can convert dp to pixels using TypedValue#applyDimension():

int pixels = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                                             getResources().getDisplayMetrics());
O.O.Balance
  • 2,930
  • 5
  • 23
  • 35