RxAndroid防止按钮短时间内被重复点击多次

  • 导入依赖
compileio.reactivex:rxandroid:1.2.1compileio.reactivex:rxjava:1.1.6
  • 添加权限
//获得写sd卡的权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
//获得读sd卡的权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
//读取网络的权限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
  • 创建一个class类:MyOnSubscribe.java
public class MyOnSubscribe implements Observable.OnSubscribe<View> {

        public MyOnSubscribe(View view) {
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    System.out.println("我被狂点中...");
                    //发布通知
                    mSubscriber.onNext(view);
                }
            });
        }
        private Subscriber mSubscriber;

        @Override
        public void call(Subscribersuper View> subscriber) {
            mSubscriber = subscriber;
        }
    }
  • 在要写点击事件的类中将点击事件换成下面的方法(这里是button)
private void RxAndroidClick() {
//mButton是按钮的对象
    Observable.create(new MyOnSubscribe(mButton))
      .throttleFirst(1, TimeUnit.SECONDS)
       .subscribe(new Action1() {
           @Override
           public void call(View view) {
               System.out.println("我在call方法中,我被点击了,有反应了");
           }
         });
    }

你可能感兴趣的:(andr实用方法)