Android常用代码集合

文章目录

    • 获取view基于窗口中的坐标
    • 获取屏幕的宽高
    • dp转px
    • px转dp
    • px转sp
    • sp转px

获取view基于窗口中的坐标

private int[] getCoordinate(View view)

{int[] location = new int[2];

​	view.getLocationOnScreen(location);int x = localtion[0];int y = location[1];Log.d("test","x:" + x + ",y:" + y);return location;

}

获取屏幕的宽高

private void getWH(Context ctx)

{WindowManager wm = (WindowManager)ctx.getSystemService(Context.WINDOW_SERVICE);DisplayMetrics outMetrics = new DisplayMetrics();

​	wm.getDefaultDisplay().getRealMetrics(outMetrics);\

​	int width = outMetrics.widthPixels;int height = outMetrics.heightPixels;Log.d("test","width:" + width + ",height:" + height);

}


dp转px

private int dip2px(Context context, float dpValue)
{final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dpValue * scale + 0.5f);
}

px转dp

  • 方法一

    public static int px2dip(Context context, int pxValue) 
    {
       return ((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, pxValue, 			                      context.getResources().getDisplayMetrics()));       
    }
    
  • 方法二

    /**DisplayMetrics类中属性density*/
    public static int px2dip(Context context, float pxValue)
    {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int)(pxValue / scale + 0.5f);
    }
    

px转sp

/*** 将px值转换为sp值,保证文字大小不变* DisplayMetrics类中属性scaledDensity*/
public static int px2sp(Context context, float pxValue)
{
    final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
    return (int)(pxValue / fontScale + 0.5f);
}

sp转px

/*** 将sp值转换为px值,保证文字大小不变* DisplayMetrics类中属性scaledDensity*/
public static int sp2px(Context context, float spValue) 
{
    final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
    return (int)(spValue * fontScale + 0.5f);
}

你可能感兴趣的:(Android开发,android,java)