2011-03-27 34 views
4

我在XML文件中定义的DP尺寸,像这样:Android的XML定义尺寸值产生意想不到的效果

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <dimen name="custom_button_Margin">10dp</dimen> 
</resources> 

的想法是,我使用这些值来设置元素之间的空白。这在我的布局XML文件中使用该值时正常工作。

段:

<RelativeLayout 
    android:id="@+id/mainButtons" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_weight="0.4" 
    android:layout_margin = "5dp" 

    android:gravity="right|bottom"> 
    <Button 
     android:id="@+id/_7" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/seven" 

     android:background = "@drawable/custom_button" 
     android:typeface="monospace" 
     android:textSize="@dimen/custom_button_TextSize" 

     android:layout_marginRight = "@dimen/custom_button_Margin" 
     android:layout_marginBottom = "@dimen/custom_button_Margin" 
    /> 
</RelativeLayout> 

当我尝试以编程方式获取此值的问题所在。我希望能得到一个与屏幕密度相匹配的值。那么我会做的就是按照公式发现here(页面很长找dp单位转换为像素为单位

我包检索的文件中定义的值的函数公式,秤它像素。

private int get_custom_button_PadV() 
    { 
    final float scale = getResources().getDisplayMetrics().density; 

    return (int) (R.dimen.custom_button_Margin * scale + 0.5f); 
    } 

当我看的代码,我看到下面的值

scale = 1.0 
R.dimen.custom_button_Margin = 2131099650 

我想不通为什么custom_button_Margin值是如此之大......我希望,随着1.0的比例,那会有一个值10.我错过了什么?

回答

8

您正在使用维度ID作为维度值。试试这个:

private int get_custom_button_PadV() { 
    final Resources res = getResources(); 
    final float scale = res.getDisplayMetrics().density; 
    return (int) (res.getDimension(R.dimen.custom_button_Margin) * scale + 0.5f); 
} 
+0

感谢您的解释。这完全解决了这个问题。 – paradoX 2011-03-27 18:07:46

相关问题