在res/values/ dimen s.xml 里面加上了这么一段:
< dimen name = "grid_hdpi_port_width" > 431px </ dimen >
< dimen name = "grid_hdpi_port_width_dp" > 431dp </ dimen >
< dimen name = "grid_hdpi_port_width_sp" > 431sp </ dimen >
< dimen name = "grid_hdpi_port_width_pt" > 431pt </ dimen >
< dimen name = "grid_hdpi_port_width_mm" > 431mm </ dimen >
< dimen name = "grid_hdpi_port_width_in" > 431in </ dimen >
然后在代码里面读取 :
Log.i ( TAG , "at the beginnig of init" );
Resources res = mContext .getResources();
float grid_hdpi_port_width = res.getDimension(R.dimen. grid_hdpi_port_width );
Log.e ( TAG , "grid_hdpi_port_width = " + grid_hdpi_port_width);
float grid_hdpi_port_width_dp = res.getDimension(R.dimen. grid_hdpi_port_width_dp );
Log.e ( TAG , "grid_hdpi_port_width_dp = " + grid_hdpi_port_width_dp);
float grid_hdpi_port_width_sp = res.getDimension(R.dimen. grid_hdpi_port_width_sp );
Log.e ( TAG , "grid_hdpi_port_width_sp = " + grid_hdpi_port_width_sp);
float grid_hdpi_port_width_pt = res.getDimension(R.dimen. grid_hdpi_port_width_pt );
Log.e ( TAG , "grid_hdpi_port_width_pt = " + grid_hdpi_port_width_pt);
float grid_hdpi_port_width_mm = res.getDimension(R.dimen. grid_hdpi_port_width_mm );
Log.e ( TAG , "grid_hdpi_port_width_mm = " + grid_hdpi_port_width_mm);
float grid_hdpi_port_width_in = res.getDimension(R.dimen. grid_hdpi_port_width_in );
Log.e ( TAG , "grid_hdpi_port_width_in = " + grid_hdpi_port_width_in);
得到是这样的 log :
mdpi时:
09-08 08:08:23.880: INFO/Test(2676): at the beginnig of init
09-08 08:08:23.890: ERROR/ Test (2676): grid_hdpi_port_width = 431.0
09-08 08:08:23.890: ERROR/ Test (2676): grid_hdpi_port_width_dp = 431.0
09-08 08:08:23.890: ERROR/ Test (2676): grid_hdpi_port_width_sp = 431.0
09-08 08:08:23.890: ERROR/ Test (2676): grid_hdpi_port_width_pt = 960.2983
09-08 08:08:23.890: ERROR/ Test (2676): grid_hdpi_port_width_mm = 2722.1055
09-08 08:08:23.890: ERROR/ Test (2676): grid_hdpi_port_width_in = 69141.48
hdpi时:
09-08 16:14:59.570: INFO/ Test (1544): at the beginnig of init
09-08 16:14:59.570: ERROR/ Test (1544): grid_hdpi_port_width = 431.0
09-08 16:14:59.570: ERROR/ Test (1544): grid_hdpi_port_width_dp = 646.5
09-08 16:14:59.570: ERROR/ Test (1544): grid_hdpi_port_width_sp = 646.5
09-08 16:14:59.570: ERROR/ Test (1544): grid_hdpi_port_width_pt = 960.2983
09-08 16:14:59.570: ERROR/ Test (1544): grid_hdpi_port_width_mm = 2722.1055
09-08 16:14:59.570: ERROR/ Test (1544): grid_hdpi_port_width_in = 69141.48
这样意味着得到的 float 默认的单位是 px 。
PS: android可以有多种设备,hdpi, mdpi, ldpi, 既然res里面已经提供了用加后缀的方式控制不同device不同orientation的时候的取值,我想我们还是应该尽可能避开在代码里面在做判断设定。比如在不同的layout目录下写不同的layout排布方式,比如说layout类似的话,可以在values下控制不同的值,可能是尺寸,也可能是个数。