非静态匿名内部类会保留外部类的引用,可能会导致外部类(如Activity)内存不能正常回收,解决方法:
1.使用非匿名类
private Handler handler = new Handler(new Handler.Callback() {
public boolean handleMessage(Message msg) {
if (msg.what == 1) {
tv2.append((String) msg.obj);
return true;
} else {
tv2.setText("");
return true;
}
}
});
2.使用弱引用
class MainActivityMHandler extends Handler{
private final WeakReference<MainActivity> mTarget ;
public MainActivityMHandler(MainActivity act){
mTarget = new WeakReference<MainActivity>(act);
}
public void handleMessage(Message msg) {
MainActivity act = mTarget.get();
if(act != null) {
if (msg.what == 1) {
act.tv2.append((String) msg.obj);
} else {
act.tv2.setText("");
}
}
}
}
private MainActivityMHandler handler = new MainActivityMHandler(this);
3.输入法不显示候选窗,并且显示完成按钮:
android:imeOptions="actionDone"
android:inputType="textNoSuggestions|textVisiblePassword"