iT邦幫忙

2022 iThome 鐵人賽

DAY 14
0
Mobile Development

Android studio 30天新手筆記系列 第 14

Day12-Android新手筆記-DataBinding

  • 分享至 

  • xImage
  •  

DataBinding 在目前使用經驗裡,幫我省去很多與UI設定相關的程式碼,如果沒使用DataBinding,我們常常需要使用findViewById、setOnClickListener等等,有了DataBinding甚至連setText都不需要。DataBinding有分為單向綁定與雙向綁定,本篇兩種使用方法都會介紹到。

/images/emoticon/emoticon27.gif

首先現在gradle的android中加入:

android{
    dataBinding{
        enabled = true
    }
}

接下來先介紹單向綁定的部分:

單向綁定

XML設定

這邊有個快速將架構建構起來的方法,如果你有順利完成上一步gradle的添加,將游標放在第二列,按下alt+enter組合鍵,參照以下圖片點擊紅色框,即可完成架構創建。

基本架構如下:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name=""
            type="" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

JAVA程式碼

先建立用來提供Data的檔案 MainModel

public class MainModel {
    String name = "Alex";
    String sex = "Male";
    String age = "18";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

接下來需要先回到XML將剛剛的空白補上
type後面的位置是MainModel的位置,複製位置如下:
這邊使用@{Data位置}

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="value"
            type="com.example.it_demo_databinding.MainModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{value.name}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

雙向綁定

雙向綁定的使用場景較常見的如EditText更新內容時,可以及時監聽並改變Data檔中的資料。基礎的使用方法如下:

XML設定

這邊與上方單向綁定的設置很像,唯一不同就是在值的綁定上,單向綁定時用的是@{Data位置},在雙向綁定中只需加上一個等號,如:@={Data位置},就可以完成基礎的雙向綁定。延續上方那個例子,這次加上一個EditText,它將改變TextView的值,使用EditText的監聽實現textView及時更新:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="value"
            type="com.example.it_demo_databinding.MainModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <EditText
            android:id="@+id/editText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName"
            android:text="@={value.name}"
            app:layout_constraintBottom_toTopOf="@+id/textView"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{value.name}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

JAVA程式碼

public class MainActivity extends AppCompatActivity {
    //這邊作為Data來源
    MainModel mainModel;
    //ActivityMainBinding由系統建立
    //如果沒有可能是忘記 Make Project => 上方導航列 -> Build -> Make Project
    ActivityMainBinding mainBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        mainModel = new MainModel();
        //將View與Model綁定
        mainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main);
        mainBinding.setValue(mainModel);

        mainBinding.editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //內容變化前
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //內容變化中
                mainBinding.setValue(mainModel);
            }

            @Override
            public void afterTextChanged(Editable s) {
                //內容變化後
                mainBinding.setValue(mainModel);
            }
        });
    }
}

每次更新EditText值的時候,如果TextView的值要跟著變動,就必須在每次更新時,都對DataBinding進行一次Set。

EditText監聽提供三個方法,分別如下:

  1. beforeTextChanged內容變化前
  2. onTextChanged內容變化中
  3. afterTextChanged內容變化後

/images/emoticon/emoticon41.gif


上一篇
Day13-Android新手筆記-Intent & Bundle
下一篇
Day15-Android新手筆記-DataBinding+onClick
系列文
Android studio 30天新手筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言