正文
}
}
注意,别忘记volatile关键字哦,否则就是10重,100重也可能还是会出问题。
上面是用的最多的,还有一种静态内部类写法更推荐:
publlic class Singleton {
private Singleton() {}
private static class SingletonLoader {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonLoader.INSTANCE;
}
}
多进程Application
是不是经常发现Application里的方法执行了多次?百思不得其解。
因为当有多个进程的时候,Application会执行多次,可以通过pid来判断那些方法只执行一次,避免浪费资源。
隐式启动Service
这是Android5.0的一个改动,不支持隐式的Service调用。下面的代码在Android 5.0+上会报错:Service Intent must be explicit:
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.jayfeng.MyService");
context.startService(serviceIntent);
可改成如下:
// 指定具体Service类,或者有packageName也行
Intent serviceIntent = new Intent(context, MyService.class);
context.startService(serviceIntent);
fill_parent的寿命
在Android2.2之后,支持使用match_parent。你的布局文件里是不是既有fill_parent和match_parent显得很乱?
如果你现在的minSdkVersion是8+的话,就可以忽略fill_parent,统一使用match_parent了,否则请使用fill_parent。
ListView的局部刷新
有的列表可能notifyDataSetChanged()代价有点高,最好能局部刷新。
局部刷新的重点是,找到要更新的那项的View,然后再根据业务逻辑更新数据即可。
private void updateItem(int index) {
int visiblePosition = listView.getFirstVisiblePosition();
if (index - visiblePosition >= 0) {
//得到要更新的item的view
View view = listView.getChildAt(index - visiblePosition);
// 更新界面(示例参考)
// TextView nameView = ViewLess.$(view, R.id.name);
// nameView.setText("update " + index);
// 更新列表数据(示例参考)
// list.get(index).setName("Update " + index);
}
}
强调一下,最后那个列表数据别忘记更新, 不然数据源不变,一滚动可能又还原了。
系统日志中几个重要的TAG
// 查看Activity跳转
adb logcat -v time | grep ActivityManager
// 查看崩溃信息
adb logcat -v time | grep AndroidRuntime
// 查看Dalvik信息,比如GC
adb logcat -v time | grep "D\/Dalvik"
// 查看art信息,比如GC
adb logcat -v time | grep "I\/art"
一行居中,多行居左的TextView
这个一般用于提示信息对话框,如果文字是一行就居中,多行就居左。
在TextView外套一层wrap_content的ViewGroup即可简单实现:
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
setCompoundDrawablesWithIntrinsicBounds()
网上一大堆setCompoundDrawables()方法无效不显示的问题,然后解决方法是setBounds,需要计算大小…
不用这么麻烦,用setCompoundDrawablesWithIntrinsicBounds()这个方法最简单!