Skip to content

Latest commit

History

History
113 lines (98 loc) · 3.2 KB

File metadata and controls

113 lines (98 loc) · 3.2 KB

Android 开发常用代码块

  1. 防止Handler造成内存泄漏,避免使用非静态内部类,继承Handler时,要么是放在单独的类文件中,要么就是使用静态内部类

    privatestaticclassMyHandlerextendsHandler {
    privateWeakReference<MainActivity> activityWeakReference;
    publicMyHandler(MainActivityactivity) {
    activityWeakReference = newWeakReference<>(activity);
    }
    @OverridepublicvoidhandleMessage(Messagemsg) {
    MainActivityactivity = activityWeakReference.get();
    if (activity != null) {
    out.println(".");
    }
    }
    }

2.swiperefreshlayout,第一次进入页面的时候显示加载进度条

mSwipeRefreshLayout.post(newRunnable() {
@Overridepublicvoidrun() {
mSwipeRefreshLayout.setRefreshing(true);
}
});

3.消除A页面到A页面之间的页面,例如A->B->C->A,

Intentintent = newIntent(C.this, A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

或在AndroidManifest.xml中设置Activity的启动模式为singleTask

4.替换AndroidManifest中的占位符 build文件

buildTypes {
dev {
debuggabletrue//替换AndroidManifest中的占位符manifestPlaceholders = [
//环信应用的appkey"emAppKey": "11721dev",
]
}
test {
debuggabletrue//替换AndroidManifest中的占位符manifestPlaceholders = [
//环信应用的appkey"emAppKey": "11721test",
]
}
}

AndroidManifest.xml

 <!-- 设置环信应用的appkey -->
<meta-dataandroid:name="EASEMOB_APPKEY"android:value="${emAppKey}" />

5.拨打电话 Intent.ACTION_DIAL直接拨打 需要权限 Intent.FLAG_ACTIVITY_NEW_TASK 跳转到拨号界面,不需要权限

//原来用Intent.ACTION_DIAL,会跳到拨号界面Intentintent = newIntent(Intent.ACTION_DIAL, Uri.parse("tel:" + "10086"));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

6.webview全屏显示image

StringimgSrcHtml = "<html><img src='" + url + "' style='width:100%;height:auto'/></html>";
mWebView.loadData(imgSrcHtml, "text/html", "UTF-8");

7.Dp,Px之间的转换

publicclassDensityUtils {
publicstaticintdpToPx(intdp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, Resources.getSystem().getDisplayMetrics());
}
publicstaticintpxToDp(floatpx) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, px, Resources.getSystem().getDisplayMetrics());
}
}

8.虚线

<shapexmlns:android="http://schemas.android.com/apk/res/android"android:shape="line">
<strokeandroid:width="1dp"android:dashWidth="5dp"android:dashGap="5dp"android:color="#33000000"/>
</shape>