4

Androidでデータバインディングを使用する方法を学ぶだけです。そして、なぜBindingAdapterを静的メソッドに設定する必要があるのか​​尋ねたいと思いますか?私はそれを非静的メソッドにすることができます場合。私は何をしなければならないのですか?自分のイメージを自分のImageLoaderオブジェクトにロードする必要があります。なぜBindingAdapterが静的メソッドでなければならないのですか?

答えて

8

BindingAdapterにはがありません。は静的になります。それが静的であれば、作業がはるかに簡単です。インスタンスメソッドを使用する必要がある場合は可能ですが、DataBindingComponentを通じてインスタンスに到達する方法を提供する必要があります。

のは、あなたがインスタンスBindingAdapterを持っていることを想像してみましょう:BindingAdapterはDataBindingComponentの方法として提供されなければならないインスタンスが含まれているものは何でもクラス

public class ImageBindingAdapters { 
    private ImageLoader imageLoader; 

    public ImageBindingAdapters(ImageLoader imageLoader) { 
     this.imageLoader = imageLoader; 
    } 

    @BindingAdapter("url") 
    public void setImageUrl(ImageView imageView, String url) { 
     imageLoader.loadInto(imageView, url); 
    } 
} 

まず、。これは実装する生成されたインターフェイスであり、メソッドはクラス名に基づいています。

public class MyComponent implements DataBindingComponent { 
    @Override 
    public ImageBindingAdapters getImageBindingAdapters() { 
     //... whatever you do to create or retrieve the instance 
     return imageBindingAdapter; 
    } 
} 

これで、バインディング時にコンポーネントを提供する必要があります。たとえば、次のようになります。

@Override 
public void onCreate(Bundle icicle) { 
    super.onCreate(icicle); 
    MyBinding binding = DataBindingUtil.setContentView(this, 
      R.layout.my, new MyComponent()); 
    binding.setData(/* whatever */); 
} 

したがって、依存性注入を使用すると主に使用されます。バインディングごとにコンポーネントを変更する必要がない場合は、DataBindingUtil.setDefaultComponent()を使用することもできます。

関連する問題