调用:
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.example.propertytest.bean.MainBean;
// 调用的时候必须实现PropertyChangeListener接口
public class MainActivity extends Activity implements PropertyChangeListener{
private TextView text;
MainBean mBean;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView) findViewById(R.id.textview);
// 创建Bean的实例且添加属性监听器
mBean = new MainBean();
mBean.addPropertyChangeListener(this);
}
public void btn(View v){
// 触发属性改动的方法
mBean.setName("yoyo");
}
// 这个方法被通知属性改变
@Override
public void propertyChange(PropertyChangeEvent event) {
System.out.println(event.getNewValue().toString());
System.out.println(event.getOldValue().toString());
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
mBean.removePropertyChangeListener(this);
super.onDestroy();
}
}
Bean类:
import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; public class MainBean { private String name = "123"; public String getName() { return name; } public void setName(String name_) { String oldValue = name; name = name_;
// 向外通知属性改变方法,会自动调用propertyChange方法 changeSupport.firePropertyChange("name", oldValue, name); }
// 创建一个PropertyChangeSupport实例 private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
// 添加属性监听器 public void addPropertyChangeListener(PropertyChangeListener l) { changeSupport.addPropertyChangeListener(l); }
// 移除属性监听器 public void removePropertyChangeListener(PropertyChangeListener l) { changeSupport.removePropertyChangeListener(l); } }