2

I got stuck in this, I don't know how to convert px to dp in MarginLayout
So this is my main MarginLayout set method

public static void setMargins (View v, int l, int t, int r, int b) {
    if (v.getLayoutParams() instanceof LinearLayout.MarginLayoutParams) {
        LinearLayout.MarginLayoutParams p = (LinearLayout.MarginLayoutParams) v.getLayoutParams();
        p.setMargins(l, t, r, b);
        v.requestLayout();
     }
}

And this is on click listener where the element changes its marginLayout

ArrowUp.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if(!Switch){
            setMargins(AdditionalOperations, 0, 0, 0, 800);
            Switch = true;
        }
        else{
            setMargins(AdditionalOperations, 0, 0, 0, 715);
            Switch = false;
        }
    }
});

My goal is to conver pixels to Dp, and margin it in DP value, not px. I'm really stuck in this and can't get the idea

AmrDeveloper
  • 3,826
  • 1
  • 21
  • 30
Hexley21
  • 566
  • 7
  • 16

1 Answers1

4

Multiply your pixel values by the device display density.

final float density = context.getResources().getDisplayMetrics().density;
final int valueInDp = (int)(valueInPixels * density);

In your case would be as next:

ArrowUp.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        final float density = view.getResources().getDisplayMetrics().density;

        if(!Switch){
            setMargins(AdditionalOperations, 0, 0, 0, 800 * density);
            Switch = true;
        }
        else{
            setMargins(AdditionalOperations, 0, 0, 0, 715 * density);
            Switch = false;
       }
   }
});

Tip: As you are using constant values, you may want to cache them instead of computing the values all the time.

PerracoLabs
  • 16,449
  • 15
  • 74
  • 127