2016-06-22 7 views
3

公式のアンドロイドのドキュメントには、フラグメントやアクティビティでのデータバインディングの使い方に関するガイダンスがあります。しかし、私はかなりの量の設定でかなり複雑なピッカーを持っています。ような何か:カスタムコントロールのアンドロイドデータバインディング

class ComplexCustomPicker extends RelativeLayout{ 
    PickerViewModel model; 
} 

は、だから私の質問は、私はそれの内側に結合し、など、テキストフィールドのような個々の値をチェック/ SETINGないこと、使用するオーバーライドする必要がピッカーのどの方法ですか?

2番目の質問 - xmlファイルのピッカーにviewmodelを渡すにはどうすればいいですか?カスタム属性が必要ですか?

答えて

2

私はあなたの問題を解決するカスタムセッターを使用すると思います。開発者ガイドラインのCheck this section

私は簡単な例を挙げることができます。ビューの名前はCustomViewであり、あなたのviewmodelのViewModelあるとし、その後、あなたのクラスのいずれかで、このような方法で作成します:

@BindingAdapter({"bind:viewmodel"}) 
public static void bindCustomView(CustomView view, ViewModel model) { 
    // Do whatever you want with your view and your model 
} 

そして、あなたのレイアウトでは、次の手順を実行します。

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

    <data> 

     <variable 
      name="viewModel" 
      type="com.pkgname.ViewModel"/> 
    </data> 

    // Your layout 

    <com.pkgname.CustomView 
    // Other attributes 
    app:viewmodel="@{viewModel}" 
    /> 

</layout> 

そして、あなたのActivity使用からのViewModelを設定するには、この:

MainActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.main_activity); 
ViewModel viewModel = new ViewModel(); 
binding.setViewModel(viewModel); 

それとも、直接、カスタムビューから膨らませることができます。

LayoutViewCustomBinding binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.layout_view_custom, this, true); 
ViewModel viewModel = new ViewModel(); 
binding.setViewModel(viewModel); 
+4

また、 'PickerViewModel'をとる' ComplexCustomPicker'にセッターメソッドがあるとしたら、 'BindingAdaper'は必要ありません。 Androidのデータバインディングは、setXxxという名前のものを自動的に検索しようとします.Xxxは属性です。したがって、 'ComplexCustomPicker'に' void setViewModel(PickerViewModel) 'メソッドがある場合は、上記のように' app:viewModel = "@ {viewModel}"という属性を使用することができます。この技術は、あなたのモデルタイプにあなたのビューを結びつけていることを意味しますが、それはあなたのアプリでうまくいくかもしれません。 –

関連する問題