【问题标题】:Programmatically set ImageView position in "dp"?以编程方式在“dp”中设置 ImageView 位置?
【发布时间】:2012-09-03 07:40:52
【问题描述】:

我读过:

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】:

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

    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);
    

    【讨论】:

    • Tnx!这是我失踪的解释!像魅力一样工作!
    猜你喜欢
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    • 2014-08-12
    • 2014-01-12
    • 2012-09-25
    相关资源
    最近更新 更多