RxBinding 是 Jake Wharton 的一个开源库,它提供了一套在 Android 平台上的基于 RxJava 的 Binding API。所谓 Binding,就是类似设置 OnClickListener 、设置 TextWatcher 这样的注册绑定对象的 API。
首先需要引入lib
android Studio
compile 'com.jakewharton.rxbinding:rxbinding:0.4.0'
通过几个例子说明使用
CheckBox chekcbox = (CheckBox) findViewById(R.id.chekcbox);
//观察选择的变化
RxCompoundButton.checkedChanges(chekcbox)
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean aBoolean) {
textview.setText(aBoolean.toString());
}
});
RxJava 中 SharedPreferences的使用
//注:需要RxSharedPreferences库支持:
compile ‘com.f2prateek.rx.preferences:rx-preferences:1.0.1’
//同步SharedPreferences
SharedPreferences msharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
RxSharedPreferences rxSharedPreferences = RxSharedPreferences.create(msharedPreferences);
Preference<Boolean> xxFunction = rxSharedPreferences.getBoolean("checkbox_start", false);
CheckBox chekcbox2 = (CheckBox) findViewById(R.id.chekcbox2);
chekcbox2.setChecked(xxFunction.get());//设置保存的状态
RxCompoundButton.checkedChanges(chekcbox2)
.subscribe(xxFunction.asAction());//保存状态
//观察点击事件
Button button = (Button) findViewById(R.id.button);
RxView.clicks(button)
.subscribe(new Action1<Void>() {
@Override
public void call(Void aVoid) {
Toast.makeText(UpdateViewActivity.this, "点击", Toast.LENGTH_SHORT).show();
}
});
防止重复点击
//解决连续点击问题
Button button2 = (Button)findViewById(R.id.button2);
RxView.clicks(button2)
.throttleFirst(3, TimeUnit.SECONDS)//在一段时间内只取一个事件 第二个参数是单位
.subscribe(new Action1<Void>() {
@Override
public void call(Void aVoid) {
Toast.makeText(UpdateViewActivity.this, "防止连续点击", Toast.LENGTH_SHORT).show();
}
});
//观察EditText改变事件
tv_ed = (TextView) findViewById(R.id.tv_ed);
EditText edittext = (EditText) findViewById(R.id.edittext);
RxTextView.textChanges(edittext)
.subscribe(new Action1<CharSequence>() {
@Override
public void call(CharSequence charSequence) {
tv_ed.setText(charSequence);
}
});