com.jakewharton.rxbinding.widget.RxTextView Java Examples

The following examples show how to use com.jakewharton.rxbinding.widget.RxTextView. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SearchDebounceActivity.java    From AndroidMVVMSample with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SearchDebounceBinding binding = DataBindingUtil.setContentView(this,
            R.layout.activity_search_debounce);

    adapter = new SearchAdapter(this);
    RecyclerViewUtils.setLinearManagerAndAdapter(binding.recyclerView, adapter);
    binding.recyclerView.addItemDecoration(DividerItemDecoration.newVertical(this,
            R.dimen.list_divider_height, R.color.divider_color));

    //===========================@TODO
    //1,避免EditText没改变一次就请求一次.
    //2,避免频繁的请求,多个导致结果顺序错乱,最终的结果也就有问题.

    // 但是对于第二个问题,也不能彻底的解决. 比如停止输入400毫秒后,
    // 那么肯定会开始请求Search接口, 但是用户又会输入新的关键字,
    // 这个时候上个请求还没有返回, 新的请求又去请求Search接口.
    // 这个时候有可能最后的一个请求返回, 第一个请求最后返回,导致搜索结果不是想要的.
    //===========================@TODO

    subscription = RxTextView.textChangeEvents(binding.inputSearch)
            .debounce(400, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(getSearchObserver());
}
 
Example #2
Source File: ChooseTagFragment.java    From CodePolitan with Apache License 2.0 6 votes vote down vote up
@Override
protected void onViewReady(@Nullable Bundle savedInstanceState)
{
    fromWelcomeActivity = getArguments().getBoolean("from_welcome");
    btnDone.setVisibility(fromWelcomeActivity ? View.INVISIBLE : View.VISIBLE);
    btnDone.setOnClickListener(this::submit);
    ivClear.setOnClickListener(v -> etSearch.setText(""));
    etSearch.setOnEditorActionListener((v, actionId, event) -> {
        KeyboardUtil.hideKeyboard(getActivity(), v);
        return true;
    });
    setUpSwipeLayout();
    setUpAdapter();
    setUpRecyclerView();
    setUpController(savedInstanceState);
    RxTextView.textChanges(etSearch)
            .subscribe(charSequence -> onTextSearchChanges(charSequence.toString()));
}
 
Example #3
Source File: ChooseCategoryFragment.java    From CodePolitan with Apache License 2.0 6 votes vote down vote up
@Override
protected void onViewReady(@Nullable Bundle savedInstanceState)
{
    fromWelcomeActivity = getArguments().getBoolean("from_welcome");
    btnDone.setVisibility(fromWelcomeActivity ? View.INVISIBLE : View.VISIBLE);
    btnDone.setOnClickListener(this::submit);
    ivClear.setOnClickListener(v -> etSearch.setText(""));
    etSearch.setOnEditorActionListener((v, actionId, event) -> {
        KeyboardUtil.hideKeyboard(getActivity(), v);
        return true;
    });
    setUpSwipeLayout();
    setUpAdapter();
    setUpRecyclerView();
    setUpController(savedInstanceState);
    RxTextView.textChanges(etSearch)
            .subscribe(charSequence -> onTextSearchChanges(charSequence.toString()),
                       throwable -> Timber.e(throwable.toString()));
}
 
Example #4
Source File: PassWordInputLayout.java    From AndroidProjects with MIT License 6 votes vote down vote up
private void addTextListeners(final EditText et) {
    final ConnectableObservable<String> textSource = RxTextView
            .textChanges(et)
            .skip(1)
            .map(CharSequence::toString)
            .publish();

    addSpaceHandler(et);

    final Subscription suggestionSub = textSource.filter(input -> input.length() > 0)
            .flatMap(this::getWordSuggestion)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(this::handleWordSuggestion, Throwable::printStackTrace);

    final Subscription uiSub = textSource
            .subscribe(this::updateUi, Throwable::printStackTrace);

    final Subscription connectSub = textSource.connect();
    this.subscriptions.addAll(suggestionSub, uiSub, connectSub);
}
 
Example #5
Source File: InstantSearchDemo.java    From RxJavaExplained with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.instant_search_demo);
  searchInput = (EditText) findViewById(R.id.search_input);
  searchResult = (RecyclerView) findViewById(R.id.search_result);

  SearchResultAdapter adapter = new SearchResultAdapter();
  searchResult.setLayoutManager(new LinearLayoutManager(this));
  searchResult.setAdapter(adapter);
  searchSubscription = RxTextView.afterTextChangeEvents(searchInput)
      // Convert the event to a String
      .map(textChangeEvent -> textChangeEvent.editable().toString())
      // Perform search on computation scheduler
      .observeOn(Schedulers.computation())
      // If we get multiple events within 200ms, just emit the last one
      .debounce(200, MILLISECONDS)
      // "Convert" the query string to a search result
      .switchMap(this::searchNames)
      // Switch back to the main thread
      .observeOn(AndroidSchedulers.mainThread())
      // Set the result on our adapter
      .subscribe(adapter::setSearchResult);
}
 
Example #6
Source File: LoginInteractorImpl.java    From Saude-no-Mapa with MIT License 6 votes vote down vote up
@Override
public void validateLoginForms(EditText emailEdit, EditText passEdit, OnFormEmitted listener) {
    Observable<Boolean> emailObservable = RxTextView.textChanges(emailEdit)
            .map(inputText -> inputText.toString().matches("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                    + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"))
            .skip(1)
            .distinctUntilChanged();

    Observable<Boolean> passwordObservable = RxTextView.textChanges(passEdit)
            .map(inputText -> inputText.toString().length() < 6)
            .skip(1)
            .distinctUntilChanged();

    emailObservable.subscribe(listener::emailOnNext);

    passwordObservable.subscribe(listener::passwordOnNext);

    Observable.combineLatest(
            emailObservable,
            passwordObservable,
            (emailValid, passValid) -> emailValid && !passValid)
            .distinctUntilChanged()
            .subscribe(listener::buttonChanged);
}
 
Example #7
Source File: LoginInteractorImpl.java    From Saude-no-Mapa with MIT License 6 votes vote down vote up
@Override
public void validateReactivateForms(EditText emailEdit, EditText passEdit, OnFormEmitted listener) {
    Observable<Boolean> emailObservable = RxTextView.textChanges(emailEdit)
            .map(inputText -> inputText.toString().matches("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                    + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"))
            .skip(1)
            .distinctUntilChanged();

    Observable<Boolean> passwordObservable = RxTextView.textChanges(passEdit)
            .map(inputText -> inputText.toString().length() < 6)
            .skip(1)
            .distinctUntilChanged();

    emailObservable.subscribe(listener::emailOnNext);

    passwordObservable.subscribe(listener::passwordOnNext);

    Observable.combineLatest(
            emailObservable,
            passwordObservable,
            (emailValid, passValid) -> emailValid && !passValid)
            .distinctUntilChanged()
            .subscribe(listener::buttonChanged);
}
 
Example #8
Source File: MainActivity.java    From RxjavaSample with MIT License 6 votes vote down vote up
/**
 * EditText,每隔500ms,去响应变化
 */
private void method18() {
    mSearchEditText.setVisibility(View.VISIBLE);
    RxTextView.textChangeEvents(mSearchEditText)
            .debounce(500, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<TextViewTextChangeEvent>() {
                @Override
                public void onCompleted() {
                }

                @Override
                public void onError(Throwable e) {
                }

                @Override
                public void onNext(TextViewTextChangeEvent textViewTextChangeEvent) {
                    String changedMessage = textViewTextChangeEvent.text().toString();
                    Logger.d(TAG, changedMessage);
                    if (!TextUtils.isEmpty(changedMessage)) {
                        ToastUtil.getInstance().showToast(MainActivity.this, changedMessage);
                    }
                }
            });
}
 
Example #9
Source File: MainActivity.java    From rxSuggestions with Apache License 2.0 5 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();
    subs.add(RxTextView.afterTextChangeEvents(searchBox)
            .map(changeEvent -> changeEvent.editable().toString())
            .compose(RxSuggestions.suggestionsTransformer())
            .subscribe(this::setSuggestions, Throwable::printStackTrace));
}
 
Example #10
Source File: TopListActivity.java    From ratebeer with GNU General Public License v3.0 5 votes vote down vote up
private <T> void setupAutoComplete(List<T> items, Action1<T> onClick) {
	SimpleAutoCompleteAdapter<T> adapter = new SimpleAutoCompleteAdapter<>(new ContextThemeWrapper(this, R.style.AppTheme_Dark), items);
	filterEdit.setAdapter(adapter);
	RxView.focusChanges(filterEdit)
			.filter(hasFocus -> hasFocus)
			.subscribe(f -> filterEdit.showDropDown());
	RxAutoCompleteTextView.itemClickEvents(filterEdit)
			.doOnNext(click -> ImeUtils.hideIme(filterEdit))
			.map(click -> adapter.getItem(click.position()))
			.subscribe(onClick);
	RxTextView.textChanges(filterEdit)
			.map(text -> text.length() > 0)
			.subscribe(RxView.visibility(clearFilterButton));
}
 
Example #11
Source File: SubmitGankActivity.java    From gank.io-unofficial-android-client with Apache License 2.0 5 votes vote down vote up
@Override
public void initViews(Bundle savedInstanceState) {

  loadingDialog = LoadingDialog.newInstance();

  RxTextView.textChanges(mEdUrl)
      .map(CharSequence::toString)
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(s -> {

        if (s.contains("http")) {
          url = s;
        }
      });

  RxTextView.textChanges(mEdTitle)
      .map(CharSequence::toString)
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(s -> {

        if (!TextUtils.isEmpty(s)) {
          title = s;
        }
      });

  RxTextView.textChanges(mEdWho)
      .map(CharSequence::toString)
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(s -> {

        if (!TextUtils.isEmpty(s)) {
          who = s;
        }
      });
}
 
Example #12
Source File: ShareExternalLinkFragment.java    From kaif-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  inflater.inflate(R.menu.menu_share, menu);
  shareBtn = menu.findItem(R.id.action_share);
  shareBtn.setEnabled(false);

  RxTextView.textChanges(titleEditText)
      .map(t -> t.length() >= 3)
      .distinctUntilChanged()
      .subscribe(shareBtn::setEnabled);
}
 
Example #13
Source File: SignUpPinCodeCreationStepLayout.java    From ResearchStack with Apache License 2.0 5 votes vote down vote up
private void initializeLayout() {
    refreshState();

    RxTextView.textChanges(editText)
            .map(CharSequence::toString)
            .filter(pin -> pin.length() == config.getPinLength())
            .subscribe(pin -> {
                if (state == State.CHANGE) {
                    result.setResultForIdentifier(RESULT_OLD_PIN, pin);

                    currentPin = pin;
                    editText.setText("");
                    state = State.CREATE;
                    refreshState();
                } else if (state == State.CREATE) {
                    currentPin = pin;
                    editText.setText("");
                    state = State.CONFIRM;
                    refreshState();
                } else {
                    if (pin.equals(currentPin)) {
                        new Handler().postDelayed(() -> {
                            imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
                            result.setResult(pin);
                            callbacks.onSaveStep(StepCallbacks.ACTION_NEXT, step, result);
                        }, 300);
                    } else {
                        state = State.RETRY;
                        editText.setText("");
                        refreshState();
                    }
                }
            });

    editText.post(() -> imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
            InputMethodManager.HIDE_IMPLICIT_ONLY));
}
 
Example #14
Source File: MainActivity.java    From materialize with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    MainActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.main_activity);

    setSupportActionBar(binding.toolbar);

    searchPanelController = new SearchPanelController(binding.searchBar);

    SearchMatcher searchMatcher = new SearchMatcher(() -> searchPanelController.getKeyword().getText().toString());

    binding.apps.setAdapter(apps = new AppInfoAdapter(this, Glide.with(this),
            searchMatcher, this));

    RxTextView.afterTextChangeEvents(searchPanelController.getKeyword())
            .compose(bindToLifecycle())
            .subscribe(avoid -> {
                apps.data.applyFilter();
                binding.apps.smoothScrollToPosition(0);
            });

    iconCacheManager = new IconCacheManager(this);

    RxPackageManager
            .intentActivities(getPackageManager(), Intents.MAIN, 0)
            .map(resolve -> AppInfo.from(resolve.activityInfo, getPackageManager(), iconCacheManager))
            .filter(app -> app != null)
            .filter(app -> !app.component.getPackageName().equals(BuildConfig.APPLICATION_ID))
            .compose(filterGoodGuys())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnCompleted(() -> binding.apps.smoothScrollToPosition(0))
            .subscribe(apps.data::addWithIndex);

    UpdateUtil.checkForUpdateAndPrompt(this);
}
 
Example #15
Source File: RxValidator.java    From RxValidator with Apache License 2.0 5 votes vote down vote up
public RxValidator onValueChanged() {
  this.changeEmitter = RxTextView.textChanges(et).skip(1).map(new Func1<CharSequence, String>() {
    @Override public String call(CharSequence charSequence) {
      return charSequence.toString();
    }
  });
  return this;
}
 
Example #16
Source File: SampleActivity.java    From rx-receivers with Apache License 2.0 5 votes vote down vote up
@Override protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  // Setup views.
  setContentView(R.layout.sample_activity);
  ButterKnife.inject(this);

  // Bind views to events.
  RxTelephonyManager.phoneStateChanges(this)
      .compose(this.<PhoneStateChangedEvent>bindUntilEvent(ActivityEvent.PAUSE))
      .map(Object::toString) //
      .startWith("waiting for change") //
      .map(prefix(getString(R.string.phone_state))) //
      .subscribe(RxTextView.text(phoneStateView));

  RxWifiManager.wifiStateChanges(this)
      .compose(this.<Integer>bindUntilEvent(ActivityEvent.PAUSE))
      .map(integer -> {
        switch (integer) {
          case WifiManager.WIFI_STATE_DISABLED:
            return "wifi disabled";
          case WifiManager.WIFI_STATE_DISABLING:
            return "wifi disabling";
          case WifiManager.WIFI_STATE_ENABLED:
            return "wifi enabled";
          case WifiManager.WIFI_STATE_ENABLING:
            return "wifi enabling";
          default:
            return "unknown";
        }
      }) //
      .map(prefix(getString(R.string.wifi_state))) //
      .subscribe(RxTextView.text(wifiStateView));

  RxBatteryManager.batteryChanges(this)
      .compose(this.<BatteryState>bindUntilEvent(ActivityEvent.PAUSE))
      .map(Object::toString)
      .map(prefix(getString(R.string.battery_state))) //
      .subscribe(RxTextView.text(batteryStateView));
}
 
Example #17
Source File: MergeEditUtil.java    From Ticket-Analysis with MIT License 5 votes vote down vote up
public static Subscription getLimitEnableStateSubscription(View enableView, FuncN<Boolean> funcN, EditText... editTexts) {
    List<Observable<CharSequence>> observableList = new ArrayList<>();
    for (EditText editText : editTexts) {
        observableList.add(RxTextView.textChanges(editText));
    }

    return Observable.combineLatest(observableList, funcN)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(isEnable -> enableView.setEnabled(isEnable), throwable -> enableView.setEnabled(false));
}
 
Example #18
Source File: VideoCommentsFragment.java    From Loop with Apache License 2.0 4 votes vote down vote up
@Override
    public void onViewCreated(final View view, Bundle bundle) {
        super.onViewCreated(view, bundle);

        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);

        ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setTitle(TrestleUtility.getFormattedText(getString(R.string.comments), font));
        }

        setUpListeners();

        recyclerView.setItemAnimator(new SlideInUpAnimator());

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        layoutManager.setStackFromEnd(true);
//        layoutManager.setReverseLayout(true);
        recyclerView.setLayoutManager(layoutManager);

        recyclerView.setItemAnimator(new SlideInUpAnimator());

        videoCommentsAdapter = new VideoCommentsAdapter(getActivity());
        videoCommentsAdapter.setOnItemLongClickListener(this);

//        List<Comment> comments = mSale.getComments();
//        if (comments != null && comments.size() > 0) {
//            Collections.reverse(comments);
//            mVideoCommentsAdapter.addAll(comments);
//        }

        recyclerView.setAdapter(videoCommentsAdapter);

        recyclerView.scrollToPosition(videoCommentsAdapter.getItemCount() - 1);

//        if (commentsCollection != null) {
////            loadComments();
//
//            List<Comment> comments = commentsCollection.getComments();
//            if (comments != null && comments.size() > 0) {
//
//                Collections.reverse(comments);
//                videoCommentsAdapter.addAll(comments);
//                recyclerView.scrollToPosition(videoCommentsAdapter.getItemCount() - 1);
////
////            mVideoCommentsAdapter.addAll(comments);
//
//                if (comments.size() >= PAGE_SIZE) {
////                            mVideoCommentsAdapter.addLoading();
//                } else {
//                    isLastPage = true;
//                }
//            }
//        } else {
//
//        }



        commentChangeObservable = RxTextView.textChanges(commentEditText);

        // Checks for validity of the comment input field
        setUpCommentSubscription();

        long id = video.getId();
        if (id != -1L) {
            loadingImageView.setVisibility(View.VISIBLE);

            videoId = id;

            Call getCommentsCall = vimeoService.getComments(videoId,
                    sortByValue,
                    sortOrderValue,
                    currentPage,
                    PAGE_SIZE);
            calls.add(getCommentsCall);
            getCommentsCall.enqueue(getCommentsFirstFetchCallback);
        }
    }
 
Example #19
Source File: PinCodeActivity.java    From ResearchStack with Apache License 2.0 4 votes vote down vote up
@Override
public void onDataAuth() {
    LogExt.e(getClass(), "onDataAuth()");
    storageAccessUnregister();

    // Show pincode layout
    PinCodeConfig config = StorageAccess.getInstance().getPinCodeConfig();

    int theme = ThemeUtils.getPassCodeTheme(this);
    pinCodeLayout = new PinCodeLayout(new ContextThemeWrapper(this, theme));
    pinCodeLayout.setBackgroundColor(Color.WHITE);

    int errorColor = getResources().getColor(R.color.rsb_error);

    TextView summary = (TextView) pinCodeLayout.findViewById(R.id.text);
    EditText pincode = (EditText) pinCodeLayout.findViewById(R.id.pincode);

    toggleKeyboardAction = enable -> {
        pincode.setEnabled(enable);
        pincode.setText("");
        pincode.requestFocus();
        if (enable) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(pincode, InputMethodManager.SHOW_FORCED);
        }
    };

    RxTextView.textChanges(pincode).map(CharSequence::toString).doOnNext(pin -> {
        if (summary.getCurrentTextColor() == errorColor) {
            summary.setTextColor(ThemeUtils.getTextColorPrimary(PinCodeActivity.this));
            pinCodeLayout.resetSummaryText();
        }
    }).filter(pin -> pin != null && pin.length() == config.getPinLength()).doOnNext(pin -> {
        pincode.setEnabled(false);
        pinCodeLayout.showProgress(true);
    }).flatMap(pin -> Observable.fromCallable(() -> {
        StorageAccess.getInstance().authenticate(PinCodeActivity.this, pin);
        return true;
    }).compose(ObservableUtils.applyDefault()).doOnError(throwable -> {
        toggleKeyboardAction.call(true);
        throwable.printStackTrace();
        summary.setText(R.string.rsb_pincode_enter_error);
        summary.setTextColor(errorColor);
        pinCodeLayout.showProgress(false);
    }).onErrorResumeNext(throwable1 -> {
        return Observable.empty();
    })).subscribe(success -> {
        if (!success) {
            toggleKeyboardAction.call(true);
        } else {
            getWindowManager().removeView(pinCodeLayout);
            pinCodeLayout = null;
            // authenticate() no longer calls notifyReady(), call this after auth
            requestStorageAccess();
        }
    });

    WindowManager.LayoutParams params = new WindowManager.LayoutParams();
    getWindowManager().addView(pinCodeLayout, params);

    // Show keyboard, needs to be delayed, not sure why
    pinCodeLayout.postDelayed(() -> toggleKeyboardAction.call(true), 300);
}
 
Example #20
Source File: TextQuestionBody.java    From ResearchStack with Apache License 2.0 4 votes vote down vote up
@Override
public View getBodyView(int viewType, LayoutInflater inflater, ViewGroup parent) {
    View body = inflater.inflate(R.layout.rsb_item_edit_text_compact, parent, false);

    editText = (EditText) body.findViewById(R.id.value);
    if (step.getPlaceholder() != null) {
        editText.setHint(step.getPlaceholder());
    } else {
        editText.setHint(R.string.rsb_hint_step_body_text);
    }

    TextView title = (TextView) body.findViewById(R.id.label);

    if (viewType == VIEW_TYPE_COMPACT) {
        title.setText(step.getTitle());
    } else {
        title.setVisibility(View.GONE);
    }

    // Restore previous result
    String stringResult = result.getResult();
    if (!TextUtils.isEmpty(stringResult)) {
        editText.setText(stringResult);
    }

    // Set result on text change
    RxTextView.textChanges(editText).subscribe(text -> {
        result.setResult(text.toString());
    });

    // Format EditText from TextAnswerFormat
    TextAnswerFormat format = (TextAnswerFormat) step.getAnswerFormat();

    editText.setSingleLine(!format.isMultipleLines());

    if (format.getMaximumLength() > TextAnswerFormat.UNLIMITED_LENGTH) {
        InputFilter.LengthFilter maxLengthFilter = new InputFilter.LengthFilter(format.getMaximumLength());
        InputFilter[] filters = ViewUtils.addFilter(editText.getFilters(), maxLengthFilter);
        editText.setFilters(filters);
    }

    Resources res = parent.getResources();
    LinearLayout.MarginLayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    layoutParams.leftMargin = res.getDimensionPixelSize(R.dimen.rsb_margin_left);
    layoutParams.rightMargin = res.getDimensionPixelSize(R.dimen.rsb_margin_right);
    body.setLayoutParams(layoutParams);

    return body;
}
 
Example #21
Source File: MainFragment.java    From YaMvp with MIT License 4 votes vote down vote up
@Override
public Flowable<CharSequence> phoneNumberChanges() {
    return RxJavaInterop.toV2Flowable(RxTextView.textChanges(mEtPhone));
}
 
Example #22
Source File: CustomListBeersAdapter.java    From ratebeer with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
	if (holder.subscriptions.hasSubscriptions())
		holder.subscriptions.clear();
	holder.beer = beers.get(position);

	boolean isHighlighted = this.highlightedItem != null && this.highlightedItem == position;
	Images.with(holder.photoImage.getContext()).loadBeer(holder.beer.beerId).placeholder(android.R.color.white).fit().centerCrop().into(holder
			.photoImage);
	holder.rowLayout.setActivated(isHighlighted);

	holder.noteText.setVisibility(isHighlighted ? View.GONE : View.VISIBLE);
	holder.noteEntryEdit.setVisibility(isHighlighted ? View.VISIBLE : View.GONE);
	holder.nameText.setText(holder.beer.beerName);
	holder.noteText.setText(holder.beer.note);
	holder.noteEntryEdit.setText(holder.beer.note);
	holder.subscriptions.add(RxTextView.textChanges(holder.noteEntryEdit).skip(1).doOnNext(holder.noteText::setText).map(note -> {
		holder.beer.note = note.toString();
		return holder.beer;
	}).subscribe(rxdb(holder.rowLayout.getContext()).put()));

	holder.starsButton.setBackgroundResource(ImageUrls.getColor(position));
	holder.starsText.setVisibility(holder.beer.stars == null || holder.beer.stars == 0 ? View.GONE : View.VISIBLE);
	holder.starsEmpty.setVisibility(holder.beer.stars == null || holder.beer.stars == 0 ? View.VISIBLE : View.GONE);
	holder.starsText.setText(String.format(Locale.getDefault(), "%1$d", holder.beer.stars));
	holder.starsEntryRating.setRating(holder.beer.stars == null? 0: holder.beer.stars);
	holder.starsEntryRating.setVisibility(isHighlighted ? View.VISIBLE : View.GONE);
	holder.subscriptions.add(RxRatingBar.ratingChanges(holder.starsEntryRating).skip(1).doOnNext(rating -> {
		boolean showRating = rating != null && rating > 0F;
		RBLog.d("Rating: " + rating);
		holder.starsText.setText(String.format(Locale.getDefault(), "%1$d", rating == null ? null : rating.intValue()));
		if (showRating && holder.starsText.getVisibility() != View.VISIBLE)
			Animations.fadeFlip(holder.starsText, holder.starsEmpty);
		else if (!showRating && holder.starsEmpty.getVisibility() != View.VISIBLE)
			Animations.fadeFlip(holder.starsEmpty, holder.starsText);
	}).map(rating -> {
		holder.beer.stars = rating == null || rating == 0F ? null : rating.intValue();
		return holder.beer;
	}).subscribe(rxdb(holder.rowLayout.getContext()).put()));

	holder.openBeerButton.setVisibility(isHighlighted ? View.VISIBLE : View.GONE);
	holder.openBeerButton.setOnClickListener(v -> {
		Context context = holder.openBeerButton.getContext();
		context.startActivity(BeerActivity.start(context, holder.beer.beerId));
	});
	holder.removeBeerButton.setVisibility(isHighlighted ? View.VISIBLE : View.GONE);
	holder.subscriptions.add(RxView.clicks(holder.removeBeerButton).subscribe(v -> {
		rxdb(holder.removeBeerButton.getContext()).delete(holder.beer);
	}));

	holder.rowLayout.setOnClickListener(v -> {
		Integer existingHighlightedItem = this.highlightedItem;
		if (existingHighlightedItem != null && existingHighlightedItem == holder.getAdapterPosition())
			// We were highlighted: close item
			this.highlightedItem = null;
		else
			this.highlightedItem = holder.getAdapterPosition();
		if (holder.noteEntryEdit.hasFocus()) {
			holder.noteEntryEdit.clearFocus();
		}
		ImeUtils.hideIme(holder.noteEntryEdit);
		if (this.highlightedItem != null && existingHighlightedItem != null)
			// Close last highlighted item
			notifyItemChanged(existingHighlightedItem);
		notifyItemChanged(holder.getAdapterPosition());
	});
}
 
Example #23
Source File: LoginActivity.java    From hacker-news-android with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    DaggerViewModelComponent.builder()
                            .appComponent(HackerNewsApplication.getAppComponent())
                            .build()
                            .inject(this);
    ButterKnife.inject(this);

    // Creates Observables from the EditTexts and enables the login button if they aren't empty
    final Observable<Boolean> userNameObservable = RxTextView.textChanges(mUsername)
                                                                 .map(charSequence -> !TextUtils.isEmpty(charSequence));
    final Observable<Boolean> passwordObservable = RxTextView.textChanges(mPassword)
                                                                 .map(charSequence-> !TextUtils.isEmpty(charSequence));
    Observable.combineLatest(userNameObservable, passwordObservable,
                             (usernameFilled, passwordFilled) -> usernameFilled && passwordFilled)
              .subscribe(fieldsFilled -> {
                  mLoginButton.setProgress(0);
                  mLoginButton.setEnabled(fieldsFilled);
              });

    RxView.clicks(mLoginButton)
                  .subscribe(button -> {
                      mLoginButton.setIndeterminateProgressMode(true);
                      mLoginButton.setProgress(50);
                      getViewModel().login(mUsername.getText().toString(), mPassword.getText().toString())
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new Subscriber<User>() {
                                        @Override
                                        public void onCompleted() {
                                            LocalBroadcastManager.getInstance(LoginActivity.this)
                                                                 .sendBroadcast(new Intent(LOGIN_SUCCESS));
                                            LoginActivity.this.finish();
                                        }

                                        @Override
                                        public void onError(Throwable e) {
                                            UIUtils.showToast(LoginActivity.this, "Something went wrong!");
                                            mLoginButton.setProgress(-1);
                                        }

                                        @Override
                                        public void onNext(User user) {
                                            if (user == null) {
                                                mLoginButton.setProgress(-1);
                                            }
                                            else {
                                                mLoginButton.setProgress(100);
                                            }
                                        }
                                    });
                  });
    if (BuildConfig.DEBUG) {
        mUsername.setText("testerCookie");
    }
}
 
Example #24
Source File: CustomListActivity.java    From ratebeer with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_customlist);

	// Set up toolbar
	Toolbar mainToolbar = setupDefaultUpButton();
	mainToolbar.inflateMenu(R.menu.menu_delete);

	EditText listNameEdit = (EditText) findViewById(R.id.list_name_edit);
	beersList = (RecyclerView) findViewById(R.id.beers_list);
	emptyText = (TextView) findViewById(R.id.empty_text);

	customListBeersAdapter = new CustomListBeersAdapter();
	beersList.setLayoutManager(new LinearLayoutManager(this));
	beersList.setAdapter(customListBeersAdapter);

	long listId = getIntent().getLongExtra("listId", 0);
	if (listId > 0) {
		list = database(this).get(CustomList.class, listId);
		listNameEdit.setText(list.name);
	} else {
		// Create and directly save, such that we have an id to bind beers to
		list = new CustomList();
		rxdb(this).put(list);
	}

	// Allow deleting the entire list
	RxToolbar.itemClicks(mainToolbar).compose(onUi())
			.filter(item -> item.getItemId() == R.id.menu_delete).compose(toIo())
			.flatMap(event -> Db.deleteCustomList(this, list)).compose(toUi())
			.doOnEach(RBLog::rx)
			.first().toCompletable()
			.subscribe(this::finish, e -> Snackbar.show(this, R.string.error_unexpectederror));

	// Directly persist name changes
	RxTextView.textChanges(listNameEdit)
			.map(name -> {
				list.name = name.toString();
				return list;
			})
			.compose(bindToLifecycle())
			.subscribe(rxdb(this).put(), e -> RBLog.e("Error persisting the list name", e));

	// Directly visualize item changes
	Db.getCustomListBeerChanges(this, list._id)
			.compose(bindToLifecycle())
			.subscribe(
					change -> customListBeersAdapter.change(change),
					e -> RBLog.e("Error handling a beer list change", e));

	// Load current beers list and always have it update the empty view visibility when adding/removing beers
	Db.getCustomListBeers(this, list._id)
			.toList()
			.compose(onIoToUi())
			.compose(bindToLifecycle())
			.subscribe(
					beers -> customListBeersAdapter.init(beers),
					e -> Snackbar.show(this, R.string.error_unexpectederror));
	RxRecyclerViewAdapter.dataEvents(customListBeersAdapter)
			.filter(event -> event.getKind() != RecyclerAdapterDataEvent.Kind.RANGE_CHANGE)
			.subscribe(event -> {
				emptyText.setVisibility(customListBeersAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
				beersList.setVisibility(customListBeersAdapter.getItemCount() == 0 ? View.GONE : View.VISIBLE);
			}, e -> RBLog.e("Unexpected error when handling list addition/removal", e));
}
 
Example #25
Source File: EditProfileActivity.java    From Saude-no-Mapa with MIT License 4 votes vote down vote up
@Override
public Observable<CharSequence> registerBioObservable() {
    return RxTextView.textChanges(aboutEditText);
}
 
Example #26
Source File: RegisterActivity.java    From Saude-no-Mapa with MIT License 4 votes vote down vote up
@Override
public Observable<CharSequence> registerPasswordObservable() {
    return RxTextView.textChanges(passwordEditText);
}
 
Example #27
Source File: DebounceActivity.java    From RxJava_RxAndroid with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_debounce);

    editText = (EditText) findViewById( R.id.editText );
    listView = (ListView) findViewById( R.id.listview );

    final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1 );
    listView.setAdapter( adapter );

    RxTextView.textChanges( editText )
            .debounce( 600 , TimeUnit.MILLISECONDS )
            .map(new Func1<CharSequence, String>() {
                @Override
                public String call(CharSequence charSequence) {
                    //get the keyword
                    String key = charSequence.toString() ;
                    return key ;
                }
            })
            .observeOn( Schedulers.io() )
            .map(new Func1<String, List<String>>() {
                @Override
                public List<String> call(String keyWord ) {
                    //get list
                    List<String> dataList = new ArrayList<String>() ;
                    if ( ! TextUtils.isEmpty( keyWord )){
                        for ( String s : getData()  ) {
                            if (s != null) {
                                if (s.contains(keyWord)) {
                                    dataList.add(s);
                                }
                            }
                        }
                    }
                    return dataList ;
                }
            })
            .observeOn( AndroidSchedulers.mainThread() )
            .subscribe(new Action1<List<String>>() {
                @Override
                public void call(List<String> strings) {
                    adapter.clear();
                    adapter.addAll( strings );
                    adapter.notifyDataSetChanged();
                }
            }) ;
}
 
Example #28
Source File: TotalCostView.java    From Defrag with Apache License 2.0 4 votes vote down vote up
@NonNull @Override public Observable<CharSequence> onTotalCostChanged() {
	return RxTextView.textChanges(editText);
}
 
Example #29
Source File: TotalCostView.java    From Defrag with Apache License 2.0 4 votes vote down vote up
@NonNull @Override public Observable<?> onSubmit() {
	return Observable.merge(RxView.clicks(floatingActionButton),
			RxTextView.editorActions(editText));
}
 
Example #30
Source File: ClaimPromotionDialogFragment.java    From aptoide-client-v8 with GNU General Public License v3.0 4 votes vote down vote up
@Override public Observable<TextViewAfterTextChangeEvent> editTextChanges() {
  return RxTextView.afterTextChangeEvents(walletAddressEdit);
}