android笔记

开发中经常要去寻找一些常用的方法,做个整理方便以后观看

1.获取当前屏幕宽高:

DisplayMetrics metric = new DisplayMetrics();  
getWindowManager().getDefaultDisplay().getMetrics(metric);  
int width = metric.widthPixels;     // 屏幕宽度(像素)  
int height = metric.heightPixels;   // 屏幕高度(像素)  
float density = metric.density;      // 屏幕密度(0.75 / 1.0 / 1.5)  
int densityDpi = metric.densityDpi;  // 屏幕密度DPI(120 / 160 / 240)  

2.在代码中设置如何设置dip

设置10dip的像素,第一个参数是类型,第二个参数是设置的值,第三个获取当前的尺度
int screenPaading = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 
                10, getResources().getDisplayMetrics())

3.在代码中设置TextView中画线和下划线

textView.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG ); //下划线

textView.getPaint().setAntiAlias(true);//抗锯齿

textview.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG); //中划线

setFlags(Paint. STRIKE_THRU_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG);  // 设置中划线并加清晰 

textView.getPaint().setFlags(0); 

4.在代码中设置文字样式

//第一步,在assets目录下新建fonts目录,把ttf字体文件放到这。
//第二步,程序中调用:
AssetManager mgr=getAssets();//得到AssetManager
Typeface tf=Typeface.createFromAsset(mgr, "fonts/ttf.ttf");//根据路径得到Typeface
tv.setTypeface(tf);//设置字体

5.代码设置textview部分变色

textview.setText(Html.fromHtml("text1<font color=red>需要改变的字体font>"));

6.获取sdcard路径

    private String getSDCardPath() {  
        File sdcardDir = null;  
        // 判断SDCard是否存在  
        boolean sdcardExist = Environment.getExternalStorageState().equals(  
                android.os.Environment.MEDIA_MOUNTED);  
        if (sdcardExist) {  
            sdcardDir = Environment.getExternalStorageDirectory();  
        }  
        return sdcardDir.toString();  
    } 

7.获取应用版本信息

        /**
         * 获取版本号
         * @return 当前应用的版本号
         */
        public void getVersion() {
            try {
                PackageManager manager = this.getPackageManager();
                PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
                versionName = info.versionName;
                versionCode = info.versionCode;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

8.判断指定service是否在运行

    /**
     * 判断指定service是否已经在运行 
     * @param serviceName
     * @return
     */
    public  boolean isWorked(String serviceName) {  
          ActivityManager myManager = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);  
          ArrayList runningService = (ArrayList) myManager.getRunningServices(30);  
          for(int i = 0 ; iif (runningService.get(i).service.getClassName().toString().equals(serviceName)) {  
                return true;  
              }
    }  

9.判断是否要影藏软键盘

    InputMethodManager imm = (InputMethodManager)
                getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            //隐藏软键盘
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        } else if (!imm.isActive()) {
            //显示软键盘
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }

10.判断网络是否连接

    //是否连接网络
    public boolean isNewworkConnect() {
        ConnectivityManager manager = (ConnectivityManager) mContext.
                getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo net = manager.getActiveNetworkInfo();
                if (net != null && net.isConnected()) {
                    return true;
                }
                 return false;
    }

11. andorid 布局文件声明引用自定义属性标签

xmlns:app="http://schemas.android.com/apk/res-auto"

12. andorid 文字适配多屏幕

res/values/dimens.xml

res/values-small/dimens.xml

res/values-normal/dimens.xml

res/values-large/dimens.xml

res/values-xlarge/dimens.xml

13. andorid 异步线程 回调细节

       //判断回调activity 是否已经被销毁
       if (getActivity().isFinishing()) {
             return;
       }

14. andorid activity 跳转 不增加内存

Intent i = new Intent("com.you.yourActivityB");
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);

15. andorid 获取 内部存储路径(data/data)

getFilesDir() //获取内部存储路径
或者
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;

try {
  outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
  outputStream.write(string.getBytes());
  outputStream.close();
} catch (Exception e) {
  e.printStackTrace();
}

16. andorid 发送邮件

Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, email);
intent.setData(Uri.parse("mailto:"+email));
intent.putExtra(Intent.EXTRA_SUBJECT, emailSubject);
intent.putExtra(Intent.EXTRA_TEXT, emailContent);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_FROM_BACKGROUND);
try {

    startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    Log.d("Email error:",e.toString());
}

17. andorid 获取控件高宽

@Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    }
    或
    View.post(new Runnable() {
        @Override
        public void run() {

        }
    });

18. andorid drawable.xml 多个背景切换

my_drawable.xml

<level-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:maxLevel="0">
        <shape android:shape="oval">
            <solid android:color="@color/red"/>
            <stroke android:width="1sp" android:color="@color/border" />
        shape>
    item>
    <item android:maxLevel="1">
        <shape android:shape="oval">
            <solid android:color="@color/green"/>
            <stroke android:width="1sp" android:color="@color/border" />
        shape>
    item>
    <item android:maxLevel="2">
        <shape android:shape="oval">
            <solid android:color="@color/blue"/>
            <stroke android:width="1sp" android:color="@color/blue" />
        shape>
    item>
level-list>
MyActivity.java

// myView is a View (or a subclass of View) 
// with background set to R.drawable.my_drawable
myView.getBackground().setLevel(0); // Set color to red
myView.getBackground().setLevel(1); // Set color to green
myView.getBackground().setLevel(2); // Set color to blue

// myImageView is an ImageView with its source
// set to R.drawable.my_drawable
myImageView.setImageLevel(0); // Set color to red
myImageView.setImageLevel(1); // Set color to green
myImageView.setImageLevel(2); // Set color to blue

19. andorid 检测是否有符合条件的activity

Intent intent = new Intent(Intent.ACTION_VIEW);  
            intent.setDataAndType(Uri.parse(url), mimetype);  
            if (getPackageManager().resolveActivity(intent,  
                        PackageManager.MATCH_DEFAULT_ONLY) != null) {  
                // someone knows how to handle this mime type with this scheme, don't download.  
                try {  
                    startActivity(intent);  
                    return;  
                } catch (ActivityNotFoundException ex) {  
                    if (Config.LOGD) {  
                        Log.d(LOGTAG, "activity not found for " + mimetype  
                                + " over " + Uri.parse(url).getScheme(), ex);  
                    }  

                }  

20. andorid activity 监听返回键

    @Override
    public void onBackPressed() {

    }

21. andorid 判断存储空间是否足够

    public static boolean isEnoughSpace(long fileSize) { // 视频缓存是否有足够的空间
        LogUtil.d(TAG, "fileSize=" + fileSize + ", 缓存可用=" + new File(getVideoCacheDir()).getUsableSpace());
        return new File(getVideoCacheDir()).getUsableSpace() >= fileSize;
    }

22. android 利用反射检查当前app的通知消息是否被关闭

public class NotificationsUtils {

private static final String CHECK_OP_NO_THROW = "checkOpNoThrow";
private static final String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

public static boolean isNotificationEnabled() {

    AppOpsManager mAppOps = (AppOpsManager) GlobalContext.getContext().getSystemService(Context.APP_OPS_SERVICE);

    ApplicationInfo appInfo = GlobalContext.getContext().getApplicationInfo();

    String pkg = GlobalContext.getContext().getApplicationContext().getPackageName();

    int uid = appInfo.uid;

    Class appOpsClass = null; /* Context.APP_OPS_MANAGER */

    try {

        appOpsClass = Class.forName(AppOpsManager.class.getName());

        Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE, String.class);

        Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
        int value = (int)opPostNotificationValue.get(Integer.class);

        return ((int)checkOpNoThrowMethod.invoke(mAppOps,value, uid, pkg) == AppOpsManager.MODE_ALLOWED);

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return false;
}
}

21. andorid 隐藏软件盘

View view = activity.getCurrentFocus();
        if (view == null) {
            view = new View(this);
        }
        //隐藏软键盘
        InputMethodManager imm = (InputMethodManager)
                getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
注意:在此activity 再 manifest中不能声明: android:windowSoftInputMode="stateHidden|adjustPan" 属性, 否则无效。

21. andorid NestedScrollView 内嵌 viewPager

    .support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">
            .support.v4.view.ViewPager
                android:id="@+id/other_person_page_viewpage"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

            .support.v4.view.ViewPager>

    .support.v4.widget.NestedScrollView>

22. 跳转到指定app设置页面(用于设置权限)

    Intent intent = new Intent();
    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    Uri uri = Uri.fromParts("package", getPackageName(), null);
    intent.setData(uri);
    startActivity(intent);

23.String 便捷格式化


 String month = String.format("%02d", (monthOfYear + 1)); //保留2位小数, example:  1 - 01, 10 - 10
  String day = String.format("%02d", dayOfMonth);

24. mInflater.inflate返回值

    View mView = mInflater.inflate(R.layout.xxxx, parentView); // mView = parentView
        View mView = mInflater.inflate(R.layout.xxxx, parentView, false); // mView = R.layout.xxxx

25. 计算汉字和英文混合长度

    /** 
     * 计算位数 
     * @param str 
     * @return 
     */  
    public static int calculatePlaces(String str)  
    {  
        int m = 0;  
        char arr[] = str.toCharArray();  
        for(int i=0;ichar c = arr[i];  
            if((c >= 0x0391 && c <= 0xFFE5))  //中文字符  
            {  
                m = m + 2;  
            }  
            else if((c>=0x0000 && c<=0x00FF)) //英文字符  
            {  
                m = m + 1;  
            }  
        }  
        return m;  
    }  

26.TextView 部分可以点击

   SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
            SpannableString spannableString;
            String color;
            int start, end = 0;
            for (final EmployeeItem item : employeeEditList.getList()) {
                spannableString = new SpannableString(item.getValue()+ "\n" );
                color = TextUtils.isEmpty(item.getColor()) ? "a0a0a0" : item.getColor();
                start = end;
                end += spannableString.length();
                spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#" + color)), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                if (!TextUtils.isEmpty(item.getAction())) {
                    spannableString.setSpan(new ClickableSpan() {
                        @Override
                        public void onClick(View widget) {
                            switch (item.getAction()) {
                                case PHONE:
                                    Intent intent = new Intent(Intent.ACTION_DIAL);
                                    intent.setData(Uri.parse("tel:" + item.getValue()));
                                    context.startActivity(intent);
                                    break;
                                case EMAIL:
                                    Intent intentEmail = new Intent(Intent.ACTION_SENDTO);
                                    intentEmail.setType("message/rfc822");
                                    intentEmail.setData(Uri.parse("mailto:" + item.getValue()));
                                    intentEmail.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    intentEmail.addFlags(Intent.FLAG_FROM_BACKGROUND);
                                    try {
                                        EmployeeEditListActivity.this.startActivity(intentEmail);
                                    } catch (ActivityNotFoundException exception) {
                                        showToast("未发现邮件客服端");
                                    }
                            }
                        }
                    }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                stringBuilder.append(spannableString);
            }
            mViewHolder.mContentText.setText(stringBuilder);
            mViewHolder.mContentText.setMovementMethod(LinkMovementMethod.getInstance());

26. 在editText中监听KeyBack返回事件(在输入法之前)。

/**
 * Created by User on 2017/11/3.
 * 监听输入法返回事件
 */

public class KeyBackEdit extends AppCompatEditText {
    public KeyBackEdit(Context context) {
        super(context);
    }

    public KeyBackEdit(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public KeyBackEdit(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mBackKeyListener != null) {
            //在输入法之前,拦截返回事件
            mBackKeyListener.onBackClick();
        }
        return super.onKeyPreIme(keyCode, event);
    }

    public interface BackKeyListener{
        void onBackClick();
    }

    private BackKeyListener mBackKeyListener;

    public void setBackKeyListener(BackKeyListener mBackKeyListener) {
        this.mBackKeyListener = mBackKeyListener;
    }
}

27.获取状态栏高度

 int statusBarHeight1 = 0;
 int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
 if (resourceId > 0) {
      //根据资源ID获取响应的尺寸值
      statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
  }

28.TextView多行ellipsize

     if (textView.getLineCount() > 2) {
        int lineEndIndex = textView.getLayout().getLineEnd(1);
        String text = textView.getText().subSequence(0, lineEndIndex - 3) + "...";
        textView.setText(text);
     }

29. Aapt2 Exception

由于 gradle 3.0默认开启了Aapt2
在gradle.properties中关闭即可:
android.enableAapt2=false

30.EidtText hint 光标靠右

   android:textCursorDrawable="@null"

你可能感兴趣的:(一点一滴学android)