Question

I've read:

How to set margin of ImageView using code, not xml

and the comment to use "You can scale the px value using context.getResources().getDisplayMetrics().density "

Thing is, I have scale representing some values in colors, and need to point cursor to certain value.

As everything is counted in "dip"s how can I send dip grammatically, not px?

eg:

0____T_h_i_s__i_s___m_y___s_c_a_l_e_____________300dp

        ^  - My cursor pointing to 100dp (LeftMargin = 100dp)

I'm using this line of code to set it up:

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(leftMargin, 0, 0, 0);
BMIcursor.setLayoutParams(lp);
Was it helpful?

Solution

The left margin in pixels can be computed like this:

leftMarginPx = leftMarginDp * context.getResources().getDisplayMetrics().density;

So with your code:

    leftMarginDp = 100 // 100dp;
    leftMargin = leftMarginDp * context.getResources().getDisplayMetrics().density;
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.setMargins(leftMargin, 0, 0, 0);
    BMIcursor.setLayoutParams(lp);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top