A specific XML value for Android XML gives unexpected results

I defined the dp dimension in the XML file as follows:

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

The idea is that I use these values ​​to set the pad between the elements. This works great when I use a value in my layout xml file.

Excerpt:

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

The problem is that I am trying to get this value programmatically. I expect to get a value that has been scaled to fit the screen density. Then all I would do was follow the formula found here (the page has been looking for Convert dp units to pixel units for quite some time)

I wrapped the formula in a function that retrieves the value defined in the file and scales it to pixels.

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

When I look at the code, I see the following values

 scale = 1.0 R.dimen.custom_button_Margin = 2131099650 

I can’t understand why the value of custom_button_Margin is so large ... I would expect that with a scale of 1.0 it would have a value of 10. What am I missing?

+4
source share
1 answer

The size identifier is used as the dimension value. Try instead:

 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); } 
+8
source

Source: https://habr.com/ru/post/1345442/


All Articles