以编程方式在“ dp”中设置ImageView的位置?

问题描述 投票:1回答:1

我读过:

How to set margin of ImageView using code, not xml

和要使用的注释“您可以使用context.getResources()。getDisplayMetrics()。density缩放px值“]

实际上,我的刻度尺用颜色表示了一些值,需要将光标指向某个值。

由于所有内容都计入“ dip”中,我该如何以语法方式发送dip,而不是px?

例如:

0 ____ T_h_i_s__i_s ___ m_y ___ s_c_a_l_e _______________ 300dp

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

我正在使用这一行代码进行设置:

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(leftMargin, 0, 0, 0);
BMIcursor.setLayoutParams(lp);
android positioning density-independent-pixel
1个回答
4
投票

像素的左边距可以这样计算:

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

使用您的代码:

    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);
© www.soinside.com 2019 - 2024. All rights reserved.