DataBindingの使用

I.はじめに

DataBindingこれはJetPack、データとUIを分離できる双方向バインディング用のライブラリです。これがその使用の簡単な記録です

2.環境構成

以前の古いバージョンDataBindingで使用するプラグインと依存ライブラリを追加する必要もありますが、今のところ、それほど複雑である必要はなく、でのbuild.gradle単純な構成だけです。次の2つの構成方法があります。

方法1:

android {
    
    
        ...
        dataBinding {
    
    
            enabled = true
        }
    }
    

方法2:

 android {
    
    
        ...
     buildFeatures {
    
    
            dataBinding = true
            //viewBinding = true
        }
 }

3.既存のレイアウトをデータバインディングレイアウトに変換します

データバインディングを使用する場合、レイアウトは次の形式を使用する必要があります。

<layout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto">
        <data>
            <variable
                name="viewmodel"
                type="com.myapp.data.ViewModel" />
        </data>
        <ConstraintLayout... /> <!-- UI layout's root element -->
    </layout>
    

以前のレイアウトよりも多くの<layout></layout>ラベルがあることがわかります。代入演算を実際に使用しない場合は、内部のラベルを<data></data>省略できます。手動でこのレイアウトに変更すると、もう少し面倒になります。公式は簡単な方法を提供します。

まず、上記の方法を使用してデータバインディング機能を有効にする必要があります。次に、レイアウトでショートカットキーを使用します(MACはAlt + Enterを使用します)。ショートカットキーは、6行目の前の任意の空白スペースで呼び出すことができます。
ここに画像の説明を挿入

選択して確認すると、次のコードになります

<?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>

    </data>

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

        <Button
            android:id="@+id/show_dialog"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="弹出一个对话框"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/update_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            app:layout_constraintTop_toBottomOf="@+id/show_dialog"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            tools:text="value" />

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

第四に、データバインディング

データバインディング用に上記のコードを変更します

activity_main.xml

<?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="change"
            type="String" />
    </data>

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

        <Button
            android:id="@+id/show_dialog"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="弹出一个对话框"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/update_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="@{change}"
            app:layout_constraintTop_toBottomOf="@+id/show_dialog"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            tools:text="value" />

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

MainActivity.kt

class MainActivity : AppCompatActivity() {
    
    
    private val binding: ActivityMainBinding by lazy {
    
    
        ActivityMainBinding.inflate(layoutInflater)
    }
    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        binding.showDialog.setOnClickListener {
    
    
            LoginDialog().show(supportFragmentManager,"")
        }
        binding.change = "啦啦啦"
    }
}

ActivityMainBindingレイアウトがクラスを生成していることがわかります。このクラスchangeを変更することで、UIコンテンツを直接変更できます。

5、DataBindingファイル

JetPackには、ビューバインディングとデータバインディングがあります。ビューバインディングはfindViewById()操作を保存し、データバインディングはデータを直接割り当てることができます。DataBindingファイルは次の方法で生成されます

最初の方法:

private val binding: ActivityMainBinding by lazy {
    
    
        ActivityMainBinding.inflate(layoutInflater)
    }

2番目の方法:

val binding: ActivityMainBinding = DataBindingUtil.setContentView(
                this, R.layout.activity_main)

FragmentListViewまたはアダプタでRecycleViewデータバインドされたアイテムを使用している場合。次の方法を使用できます。

    val listItemBinding = ListItemBinding.inflate(layoutInflater, viewGroup, false)
    // or
    val listItemBinding = DataBindingUtil.inflate(layoutInflater, R.layout.list_item, viewGroup, false)

バインドする具体的なタイプがわからない場合があります。現時点では、次の方法を使用してバインドできます

    val viewRoot = LayoutInflater.from(this).inflate(layoutId, parent, attachToParent)
    val binding: ViewDataBinding? = DataBindingUtil.bind(viewRoot)

レイアウトが他のメカニズムを使用して拡張されている場合は、次のように個別にバインドできます。

    val binding: MyLayoutBinding = MyLayoutBinding.bind(viewRoot)

レイアウトでのタグの使用など、このメソッドはいつ使用され<include>ますか。<ViewStub>または、レイアウトを動的に追加する必要があります。このように使用できます

動的変数:
システムが特定のバインディングクラスを認識していない場合があります。たとえば、任意のレイアウトに対して実行すると、特定のバインディングクラスがわかりRecyclerView.Adapterません。onBindViewHolder()メソッドを呼び出すときは、バインディング値を指定する必要があります。

次の例では、RecyclerViewすべてのレイアウトにitem変数がバインドされています。BindingHolderオブジェクトにgetBinding()ViewDataBinding、基本クラスを返すメソッドがあります。

    override fun onBindViewHolder(holder: BindingHolder, position: Int) {
    
    
        item: T = items.get(position)
        holder.binding.setVariable(BR.item, item);
        holder.binding.executePendingBindings();
    }

:データバインディングライブラリは、データバインディングに使用されるリソースのIDを含むモジュールパッケージにBRという名前のクラスを生成します。上記の例では、ライブラリは自動的にBR.item変数を生成します。

この説明については、https ://blog.csdn.net/cunchi4221/article/details/107478770https://blog.csdn.net/mountain_eyes/article/details/80627037を参照してください

6.参照リンク

  1. はじめに|Android開発者|Android開発者

おすすめ

転載: blog.csdn.net/Mr_Tony/article/details/124199278