在不同地方通过getMeasuredWidth()方法获取宽度返回值不同

channelWidth = channelListFragment.getView().getMeasuredWidth();

在onActivityCreated方法中获取fragment的宽度,返回0

11-01 09:54:46.247: D/WatchTvFragment(4862): channelWidth:0

在onTouch方法中获取fragment的宽度,返回值不为0

11-01 09:55:44.127: D/WatchTvFragment(4862): channelWidth:533

在xml文件中定义的channelWidth的宽度是多少呢,请看fragment_watchtv.xml

从xml文件看得channel_list_fragment的宽度是400dp,为什么日志显示533呢

经过验证400dp经过换算就得到533px,换算过程跟屏幕的density有关系。

换算过程的日志:

11-01 10:11:57.437: D/WatchTvFragment(5590): channelWidth:53311-01 10:11:57.437: D/WatchTvFragment(5590): ++px2dip++11-01 10:11:57.437: D/WatchTvFragment(5590): pxValue:533.0, density:1.3312501, dipValue:40011-01 10:11:57.437: D/WatchTvFragment(5590): ++dip2px++11-01 10:11:57.447: D/WatchTvFragment(5590): dipValue:400.0, density:1.3312501, pxValue:533

换算过程代码片段:

channelWidth = channelListFragment.getView().getMeasuredWidth();Logger.i(TAG, "channelWidth:"+channelWidth);int dipValue = px2dip(getActivity(), channelWidth);dip2px(getActivity(), dipValue);

dip和px之间相互换算方法:

public static int dip2px(Context context, float dipValue) {    final float density = context.getResources().getDisplayMetrics().density;    int pxValue = (int) (dipValue * density + 0.5f);    Logger.i(TAG, "++dip2px++");    Logger.i(TAG, "dipValue:"+dipValue+", density:"+density+", pxValue:"+pxValue);    return pxValue;}public static int px2dip(Context context, float pxValue) {    final float density = context.getResources().getDisplayMetrics().density;    int dipValue = (int) (pxValue / density + 0.5f);    Logger.i(TAG, "++px2dip++");    Logger.i(TAG, "pxValue:"+pxValue+", density:"+density+", dipValue:"+dipValue);    return dipValue;}

参考链接:http://www.cnblogs.com/fbsk/archive/2011/10/17/2215539.html