android笔记
来源:互联网 发布:淘宝类目007是什么牌子 编辑:程序博客网 时间:2024/05/01 18:06
开发中经常要去寻找一些常用的方法,做个整理方便以后观看
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();//得到AssetManagerTypeface tf=Typeface.createFromAsset(mgr, "fonts/ttf.ttf");//根据路径得到Typefacetv.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<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager.getRunningServices(30); for(int i = 0 ; i<runningService.size();i++) { if (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.xmlres/values-small/dimens.xmlres/values-normal/dimens.xmlres/values-large/dimens.xmlres/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_drawablemyView.getBackground().setLevel(0); // Set color to redmyView.getBackground().setLevel(1); // Set color to greenmyView.getBackground().setLevel(2); // Set color to blue// myImageView is an ImageView with its source// set to R.drawable.my_drawablemyImageView.setImageLevel(0); // Set color to redmyImageView.setImageLevel(1); // Set color to greenmyImageView.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
<android.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"> <android.support.v4.view.ViewPager android:id="@+id/other_person_page_viewpage" android:layout_width="match_parent" android:layout_height="wrap_content"> </android.support.v4.view.ViewPager> </android.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);
0 0
- android笔记
- android笔记
- android笔记
- Android笔记
- Android笔记
- android笔记
- android 笔记
- android笔记
- Android笔记
- android笔记
- Android笔记
- Android笔记
- android笔记
- android笔记
- android笔记
- android 笔记
- android 笔记
- Android笔记
- 从零开始编写图片加载库(五)之图片缓存DiskCache
- 图解测试之稳定性-如何开始稳定性测试
- C++枚举类型
- hdu 5122 简单题
- Html学习笔记5
- android笔记
- Oracle学习笔记20150908权限与角色的管理
- Android五大存储---(四大组件之一)ContentProvider(字段)
- 二叉搜索树转为双向链表(算法)
- MyBatis接口的简单实现原理
- 读
- 通过struts2.3.24实现登陆操作
- SVN命令使用详解
- hdu 2846 Repository