I have written a custom listener in my android app as below:
private OnListener l = new OnListener() {
@Override
public void OnReceive() {
Log.v(TAG, "Received response");
};
It works well, however, when I set l = null, it still invokes OnReceive(). It's probably because it runs in a separate thread and the reference to it still exists in the event caller function. However, how I can make sure if I set it to null, it doesn't receive anything? Or how can I unregister a listener?
I don't know about events and threads, but if you set a null listener to your control, it should unregister.
I tried this:
int timesFired=0;
Button btn2, btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView txt=(TextView)findViewById(R.id.textView1);
btn1=(Button)findViewById(R.id.btn1);
btn2=(Button)findViewById(R.id.btn2);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
timesFired++;
txt.setText("btn1's listener fired " + timesFired);
}
});
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
btn1.setOnClickListener(null);
txt.setText("btn1 unregistered");
}
});
}
And it does what it's supposed to.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.