データバインディングでは TextViewにテキストを設定するのが多いのだけど、GroupViewに対して子 Viewを追加したい時もある。
そんな時は BindingAdapterを使う。
親レイアウト
4942/activity_main.xml<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >
<data>
<variable name="Item4" type="jp.globefish.myapplication.TestData4"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:childviews="@{Item4.childList}"/>
</LinearLayout>
</layout>
子 Viewは適当に
4942/child_layout.xml<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="child" />
データを提供&追加
4942/TestData4.javapackage jp.globefish.myapplication;
import android.databinding.BaseObservable;
import android.databinding.BindingAdapter;
import android.view.LayoutInflater;
import android.view.ViewGroup;
public class TestData4 extends BaseObservable {
public ChildList getChildList() {
return new ChildList();
}
@BindingAdapter("app:childviews")
public static void setChildLayout(ViewGroup parent, ChildList childList) {
parent.addView(LayoutInflater.from(parent.getContext()).inflate(R.layout.child_layout, null, false));
parent.addView(LayoutInflater.from(parent.getContext()).inflate(R.layout.child_layout, null, false));
}
}
データをセットしてやる
4942/MainActivity.javapackage jp.globefish.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import jp.globefish.myapplication.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding Binding = ActivityMainBinding.inflate(getLayoutInflater());
Binding.setItem4(new TestData4());
setContentView(Binding.getRoot());
}
}
この辺は適当に
4942/ChildList.javapackage jp.globefish.myapplication;
public class ChildList {
}
これで ViewGroupを findItemByIdしてチマチマ inflateしていたのを分離できる。