监听的注册与释放
遇到内存泄漏,先去检查TextWatcher是不是忘记释放了!!!
一、OnClickListener
View.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 处理点击事件
}
});
View.setOnClickListener(null);
二、OnFocusChangeListener
View.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// 处理焦点变化事件
}
});
View.setOnFocusChangeListener(null);
三、OnCheckedChangeListener
CheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// 处理选中状态变化事件
}
});
CheckBox.setOnCheckedChangeListener(null);
四、TextWatcher
EditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int before, int count) {
// 在文本变化之前调用
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
// 在文本变化时调用
}
@Override
public void afterTextChanged(Editable editable) {
// 在文本变化之后调用
}
});
EditText.removeTextChangedListener(yourTextWatcher);
五、RecyclerView 的滚动监听器 (OnScrollListener)
RecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
// 实现滚动监听逻辑
});
RecyclerView.clearOnScrollListeners();
六、广播接收器 (BroadcastReceiver)
BroadcastReceiver receiver = new YourBroadcastReceiver();
IntentFilter filter = new IntentFilter(YourIntent.ACTION);
registerReceiver(receiver, filter);
unregisterReceiver(receiver);
七、生命周期监听器 (LifecycleObserver)
getLifecycle().addObserver(yourObserver);
getLifecycle().removeObserver(yourObserver);