碰到一个怪现象
我想动态调整layout的高度
在xml里面写了个初始值 android:layout_height="66dp"
然后运行的时候想让它变化
却发现如果设置
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 66);
这样的,倒是可以调整高度啦,但是却比原来的缩短不少
如果上面的改成0x66就跟原来的高度差不多
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 0x66);但0x66dp却不能写在xml里,类似这样 android:layout_height="0x66dp"<----报错到底是什么原因?

解决方案 »

  1.   

    android:layout_height="0x66dp"没这种写法吧,换成android:layout_height="102dp"吧
      

  2.   

    我知道android:layout_height="102dp"这种写法是可以的,但是为何LayoutParams(LayoutParams.FILL_PARENT, 102)在屏幕显示的就要短一些?写成LayoutParams(LayoutParams.FILL_PARENT, 0x102)才感觉是跟xml设置的同一高度
    xml设置和代码设置的差异在哪里?
      

  3.   

    java代码里面66代表66px,xml里面是66dp,这个跟手机分辨率有关的
      

  4.   

    看你手机分辨率1dp=1.5px,其实如果你把xml文件里面的dp换成px效果就一样了
      

  5.   

    你代码写的是像素
    而XML中写的是单位密度
    这两个需要转换
    public static int Dp2Px(Context context, float dp) {  
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (dp * scale + 0.5f);  
    }  
       
    public static int Px2Dp(Context context, float px) {  
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (px / scale + 0.5f);  
      

  6.   

     dp   sp   px   去看看这个概念。dp在android中是可以根据屏幕大小自动调整的,在代码中设置自适应要用楼上的方法,获取屏幕分辨率  或者  指定typeValue