android:orientation="vertical",Android RxBinding

 2023-11-19 阅读 21 评论 0

摘要:In the previous tutorials, we discussed RxJava and some of its operators. Today we will discuss the RxBinding library in our Android Application.android:orientation="vertical", 在之前的教程中,我們討論了RxJava及其一些運算符 。 今天,

In the previous tutorials, we discussed RxJava and some of its operators. Today we will discuss the RxBinding library in our Android Application.

android:orientation="vertical", 在之前的教程中,我們討論了RxJava及其一些運算符 。 今天,我們將在Android應用程序中討論RxBinding庫。

Rx綁定 (RxBinding)

We know that RxJava is a reactive event-based programming paradigm.
RxBinding is a set of support libraries to make the implementation of user interaction with the UI elements in Android easier.

我們知道RxJava是一種基于事件的React式編程范例。
RxBinding是一組支持庫,可簡化與Android中的UI元素的用戶交互的實現。

To use RxBinding in your application you must include:

要在您的應用程序中使用RxBinding,您必須包括:

implementation  'com.jakewharton.rxbinding2:rxbinding:2.0.0'

Using this along with the RxJava dependency:

與RxJava依賴項一起使用:

implementation  'io.reactivex.rxjava2:rxjava:2.1.9'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'

To use RxBinding with Appcompat and other submodules we simply need to import their respective rxbinding libraries:

要將RxBinding與Appcompat和其他子模塊一起使用,我們只需要導入它們各自的rxbinding庫:

  • implementation com.jakewharton.rxbinding2:rxbinding-recyclerview-v7:2.0.0'

    implementation com.jakewharton.rxbinding2:rxbinding-recyclerview-v7:2.0.0'
  • implementation 'com.jakewharton.rxbinding2:rxbinding-support-v4:2.0.0'

    implementation 'com.jakewharton.rxbinding2:rxbinding-support-v4:2.0.0'
  • implementation 'com.jakewharton.rxbinding2:rxbinding-appcompat-v7:2.0.0'

    implementation 'com.jakewharton.rxbinding2:rxbinding-appcompat-v7:2.0.0'
  • implementation 'com.jakewharton.rxbinding2:rxbinding-design:2.0.0'

    implementation 'com.jakewharton.rxbinding2:rxbinding-design:2.0.0'
  • implementation 'com.jakewharton.rxbinding2:rxbinding-recyclerview-v7:2.0.0'

    implementation 'com.jakewharton.rxbinding2:rxbinding-recyclerview-v7:2.0.0'
  • compile 'com.jakewharton.rxbinding2:rxbinding-leanback-v17:2.0.0'

    compile 'com.jakewharton.rxbinding2:rxbinding-leanback-v17:2.0.0'

we can use RxBinding features in our application.

我們可以在應用程序中使用RxBinding功能。

RxView.click() (RxView.click())

Typically, to set click listener events on a Button, the following is the piece of code that we write:

通常,要在Button上設置點擊偵聽器事件,以下是我們編寫的代碼段:

Button b = (Button)findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Toast.makeText(getApplicationContext(),"Button clicked",Toast.LENGTH_SHORT).show();}});

Now with RxBinding we can do:

現在,使用RxBinding,我們可以執行以下操作:

Disposable d = RxView.clicks(button).subscribe(new Consumer<Object>() {@Overridepublic void accept(Object o) {Toast.makeText(getApplicationContext(),"Button clicked",Toast.LENGTH_SHORT).show();}});

Inside RxView.clicks we pass the View instance which is to be clicked.

RxView.clicks內部,我們傳遞了要單擊的View實例。

If you are new to RxJava2, Disposable is equivalent to Subscription.
For more information on changes in RxJava2 refer here.

如果您不熟悉RxJava2,則Disposable等同于Subscription。
有關RxJava2中更改的更多信息,請參見此處 。

On the Disposable instance we can unsubscribe from the event by calling d.dispose();.
The Disposable instance holds a reference to the view. So if this code is defined outside the context of the Activity, you must unsubscribe from the event to prevent memory leaks.

在Disposable實例上,我們可以通過調用d.dispose();取消訂閱該事件d.dispose();
Disposable實例包含對該視圖的引用。 因此,如果此代碼是在Activity上下文之外定義的,則必須取消訂閱該事件,以防止內存泄漏。

RxView.click() returns an Observable. So we can add RxJava operators to perform transformations and chain implementations on it.

RxView.click()返回一個Observable。 因此,我們可以添加RxJava運算符以在其上執行轉換和鏈式實現。

EditText TextChanges (EditText TextChanges)

Typically to add text change listeners on an EditText we need to implement the TextWatcher methods:

通常,要在EditText上添加文本更改偵聽器,我們需要實現TextWatcher方法:

EditText editText = findViewById(R.id.editText);
editText.addTextChangedListener(new TextWatcher() {@Overridepublic void beforeTextChanged(CharSequence s, int start, int count, int after) {}@Overridepublic void onTextChanged(CharSequence s, int start, int before, int count) {}@Overridepublic void afterTextChanged(Editable s) {}
});

Using RxBinding we can do:

使用RxBinding,我們可以執行以下操作:

Disposable d2 = RxTextView.textChanges(editText).subscribe(new Consumer<CharSequence>() {@Overridepublic void accept(CharSequence charSequence) throws Exception {//Add your logic to work on the Charsequence}});

We pass the EditText inside RxTextView.textChanges.

我們在RxTextView.textChanges內部傳遞EditText。

Now let’s see how RxJava operators and transformations give us leverage.

現在,讓我們看看RxJava運算符和轉換如何給我們帶來影響。

使用地圖運算符 (Using Map operator)

Using map operator we can change the data that is being sent.
For example, in the EditText we can change the CharSequence to a String

使用地圖運算符,我們可以更改正在發送的數據。
例如,在EditText中,我們可以將CharSequence更改為String

Disposable d2 = RxTextView.textChanges(editText).map(charSequence -> charSequence.toString()).subscribe(new Consumer<CharSequence>() {@Overridepublic void accept(String string) throws Exception {//Add your logic to work on the Charsequence}});

使用反跳運算符 (Using debounce operator)

Using a debounce operator we can delay the event action.

使用反跳運算符,我們可以延遲事件動作。

For example, on the Button click, we can set a debounce of 2 seconds. This will run the operation after 2 seconds:

例如,在“按鈕”上單擊,我們可以將去抖設置為2秒。 2秒后將運行該操作:

RxView.clicks(button).debounce(2, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).map(o -> button.getText().toString()).subscribe(new Consumer<String>() {@Overridepublic void accept(String o) throws Exception {Toast.makeText(getApplicationContext(),o + "was clicked",Toast.LENGTH_SHORT).show();}});

A debounce operation doesn’t run on the UI thread. It runs on the computational thread.
Hence you must call the main thread in the observeOn method after that as done above.

反跳操作不在UI線程上運行。 它在計算線程上運行。
因此,如上所述,您必須在此之后在observeOn方法中調用主線程。

A debounce operator is commonly used in EditText, especially in a SearchView to let the user stop typing for a few seconds before running the action/requests.

反跳運算符通常在EditText中使用,尤其是在SearchView中,可以使用戶在運行操作/請求之前停止鍵入幾秒鐘。

使用節流閥 (Using throttleFirst)

Unlike debounce which delays the action, throttleFirst operator is used in preventing repeated actions within a certain time interval.
ThrottleFirst is useful when it comes to preventing double actions when a Button is repeatedly clicked.

與防抖會延遲動作不同, throttleFirst運算符用于防止在特定時間間隔內重復動作。
ThrottleFirst對于防止重復單擊按鈕時的雙重操作很有用。

RxView.clicks(button).throttleFirst(2, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Object>() {@Overridepublic void accept(Object o) {Toast.makeText(getApplicationContext(), "Avoid multiple clicks using throttleFirst", Toast.LENGTH_SHORT).show();}});

In the above code, the Button won’t show a Toast again until after 2 seconds.

在上面的代碼中,Button直到2秒后才會再次顯示Toast。

Merging Multiple Button click actions

合并多個按鈕單擊動作

We can merge RxView.click() Observables in the following way:

我們可以通過以下方式合并RxView.click() Observables:

Button button1 = findViewById(R.id.button1);
Button button2 = findViewById(R.id.button2);
Observable<Object> observable1 = RxView.clicks(button1);
Observable<Object> observable1 = RxView.clicks(button2);Observable.merge(observable1, observable2).subscribe(new Consumer<Object>() {@Overridepublic void accept(Object o) {//This common logic would be triggered when either of them are clicked}});

Multiple Click Listeners on a Button

一個按鈕上的多個單擊偵聽器

CompositeDisposable compositeDisposable = new CompositeDisposable();Observable<Button> clickObservable = RxView.clicks(button).map(o -> button).share();Disposable buttonShowToast =clickObservable.subscribe(new Consumer<Button>() {@Overridepublic void accept(Button o) throws Exception {Toast.makeText(getApplicationContext(), "Show toast", Toast.LENGTH_SHORT).show();}});compositeDisposable.add(buttonShowToast);Disposable changeButtonText =clickObservable.subscribe(new Consumer<Button>() {@Overridepublic void accept(Button o) throws Exception {o.setText("New text");}});compositeDisposable.add(changeButtonText);

Using the share operator on the RxView.click() observable, both the Disposables created below are run when the button is clicked.

使用可觀察到的RxView.click()上的share運算符,單擊該按鈕時,將同時運行下面創建的兩個Disposable。

Let’s merge the above concepts in our Android Application with a few more operators:

讓我們在Android應用程序中將以上概念與更多運算符合并:

項目結構 (Project Structure)

(Code)

activity_main.xml

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="https://schemas.android.com/apk/res/android"xmlns:app="https://schemas.android.com/apk/res-auto"xmlns:tools="https://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><EditTextandroid:id="@+id/editText"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="Enter here!"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"app:layout_constraintTop_toTopOf="parent"app:layout_constraintVertical_bias="0.35000002" /><TextViewandroid:id="@+id/txtBelowEditText"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginEnd="8dp"android:layout_marginLeft="8dp"android:layout_marginRight="8dp"android:layout_marginStart="8dp"android:layout_marginTop="16dp"android:text="TextView"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/editText" /><Buttonandroid:id="@+id/button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Button"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintHorizontal_bias="0.5"app:layout_constraintStart_toEndOf="@+id/button2"app:layout_constraintBaseline_toBaselineOf="@+id/button2"/><Buttonandroid:id="@+id/button2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="16dp"android:text="Button2"app:layout_constraintEnd_toStartOf="@+id/button"app:layout_constraintHorizontal_bias="0.5"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /><TextViewandroid:id="@+id/txtBelowButton"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="16dp"android:text="TextView"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/button2" /><android.support.design.widget.FloatingActionButtonandroid:id="@+id/fab"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginBottom="24dp"android:layout_marginTop="8dp"android:src="@android:drawable/ic_input_add"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"/><Buttonandroid:id="@+id/button3"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Simulateneous Actions"app:layout_constraintBottom_toTopOf="@+id/fab"android:layout_margin="8dp"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"/></android.support.constraint.ConstraintLayout>

MainActivity.java

MainActivity.java

package com.journaldev.androidrxbinding;import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;import java.util.concurrent.TimeUnit;import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;public class MainActivity extends AppCompatActivity {Button button, button2, button3;FloatingActionButton fab;TextView txtBelowEditText, txtBelowButton;EditText editText;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button = findViewById(R.id.button);button2 = findViewById(R.id.button2);button3 = findViewById(R.id.button3);fab = findViewById(R.id.fab);txtBelowEditText = findViewById(R.id.txtBelowEditText);txtBelowButton = findViewById(R.id.txtBelowButton);editText = findViewById(R.id.editText);Observable<Object> observable1 = RxView.clicks(button2).map(o -> button2);Observable<Object> observable2 = RxView.clicks(fab).map(o -> fab);Disposable d1 = Observable.merge(observable1, observable2).throttleFirst(2, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Object>() {@Overridepublic void accept(Object o) {Toast.makeText(getApplicationContext(), "Avoid multiple clicks using throttleFirst", Toast.LENGTH_SHORT).show();if (o instanceof Button) {txtBelowButton.setText(((Button) o).getText().toString() + " clicked");} else if (o instanceof FloatingActionButton) {txtBelowButton.setText("Fab clicked");}}});Disposable d = RxView.clicks(button).debounce(5, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).map(o -> button.getText().toString()).subscribe(new Consumer<String>() {@Overridepublic void accept(String o) throws Exception {txtBelowButton.setText(o + " was clicked");}});Disposable d2 = RxTextView.textChanges(editText).filter(s -> s.toString().length() > 6).debounce(2, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<CharSequence>() {@Overridepublic void accept(CharSequence charSequence) throws Exception {txtBelowEditText.setText(charSequence);}});CompositeDisposable compositeDisposable = new CompositeDisposable();Observable<Button> clickObservable = RxView.clicks(button3).map(o -> button3).share();Disposable buttonShowToast =clickObservable.subscribe(new Consumer<Button>() {@Overridepublic void accept(Button o) throws Exception {Toast.makeText(getApplicationContext(), "Show toast", Toast.LENGTH_SHORT).show();}});compositeDisposable.add(buttonShowToast);Disposable changeButtonText =clickObservable.subscribe(new Consumer<Button>() {@Overridepublic void accept(Button o) throws Exception {o.setText("New text");}});compositeDisposable.add(changeButtonText);}}

In the EditText, we’ve set a filter operator which doesn’t set the input text onto the TextView until the length crosses a threshold.

在EditText中,我們設置了一個filter運算符,直到長度超過閾值時才將輸入文本設置到TextView上。

To clear all the Disposables, instead of calling disposable() on each of them separately, we can do the following as well:

要清除所有Disposable,而不是分別對每個Disposable()進行調用,我們還可以執行以下操作:

CompositeDisposable clearAllDisposables = new CompositeDisposable();clearAllDisposables.add(d1);clearAllDisposables.add(d2);clearAllDisposables.add(d);clearAllDisposables.clear();

The output of the application in action is given below:

實際應用程序的輸出如下:

Notice how many times the FloatingActionButton was clicked. But the Toast was displayed just once.

注意單擊FloatingActionButton的次數。 但是吐司只被展示了一次。

This brings an end to this tutorial. You can download the project from the link below:

本教程到此結束。 您可以從下面的鏈接下載項目:

AndroidRxBindingAndroidRxBinding
AndroidRxBindingAndroidRxBinding

翻譯自: https://www.journaldev.com/22527/android-rxbinding

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/182943.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息