Android常用代码片段

来源:互联网 发布:淘宝上的摩托车靠谱吗 编辑:程序博客网 时间:2024/05/18 03:19

一. 获取资源图片Drawable的四种方式:

//方式一Drawable drawable = mContext.getResources().getDrawable(R.drawable.image);mImageview.setBackground(drawable);//方式二InputStream is = mContext.getResources().openRawResource(R.drawable.image);  Bitmap bitmap = BitmapFactory.decodeStream(is);//方式三 Inputstream is = mContext.getResources().openRawResource(R.drawable.image);BitmapDrawable  bitmapDrawable = new BitmapDrawable(is);Bitmap bitmap = bmpDraw.getBitmap();//方式四Bitmap bitmap=BitmapFactory.decodeResource(r, R.drawable.image);

二. 从assets中读取图片和文本

  1. 从Assets中读取图片
public static Drawable getImageFromAssets(final Context context, String fileName) {        try {            InputStream is = context.getResources().getAssets().open(fileName);            return Drawable.createFromStream(is, null);        } catch (IOException e) {            if (e != null) {                e.printStackTrace();            }        } catch (OutOfMemoryError e) {            if (e != null) {                e.printStackTrace();            }        } catch (Exception e) {            if (e != null) {                e.printStackTrace();            }        }        return null;    }
  1. 从Assets读取文本
    public static String getTextFromAssets(final Context context, String fileName) {        String result = "";        try {            InputStream in = context.getResources().getAssets().open(fileName);            int lenght = in.available();            byte[] buffer = new byte[lenght];            in.read(buffer);            result = EncodingUtils.getString(buffer, "UTF-8");            in.close();        } catch (Exception e) {            e.printStackTrace();        }        return result;    }

三.Android 切换全屏

1.切换成全屏

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
  1. 非全屏
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

四. px, dp, sp三者互相转换

记录常用的工具方法,为了以后方便使用。

//1. dp-->px public static int dip2px(Context context, float dpValue) {     final float scale = context.getResources().getDisplayMetrics().density;     return (int) (dpValue * scale + 0.5f); }//2. px-->dppublic static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f);}//3. sp-->pxpublic static int sp2px(Context context, float spValue) { final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; return (int) (spValue * fontScale + 0.5f);}//4. px-->sppublic static int px2sp(Context context, float pxValue) { final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; return (int) (pxValue / fontScale + 0.5f);}
0 0
原创粉丝点击