如何在 MVVM 中数据绑定动态膨胀的布局

How to databind dynamically inflated layouts in MVVM

我有一个 observable 可以膨胀 3 种类型的布局

mEventActivityViewModel.getEventPhotos().observe(this, new Observer<List<EventPhotosDao.EventPhotos>>() {
    @Override
    public void onChanged(List<EventPhotosDao.EventPhotos> eventPhotos) {

        int position = eventPhotos.size();
        switch (position){
            case 0:
                initAddPhotosButton2();
                break;

            case 1:
                inflateOnePhotoLayout();
                break;

            case 2:
                inflateTwoPhotoLayout();
                break;

            default:
                inflateThreePhotoLayout();
                break;


         }
    });

我如何在 MVVM 架构中对动态扩展的布局进行数据绑定?我所有的逻辑都在我的 Activity class 中吗?

private void inflateOnePhotoLayout() {
        View eventOnePhotosLayout = (View) LayoutInflater.from(this)
                .inflate(R.layout.fragevent_photolayout_onephoto, mPhotosLayout, false);
        ImageView imageView = (ImageView) eventOnePhotosLayout.findViewById(R.id.fragevent_onephotolayout_image1);
        Glide.with(this).load(mEventPhotos.get(0).getBody()).apply(RequestOptions.centerCropTransform()).into(imageView);
        mPhotosLayout.addView(eventOnePhotosLayout);

        View eventNumPhotos_1 = (View) LayoutInflater.from(this)
                .inflate(R.layout.vh_fragevent_numberpictures, mPhotosLayout, false);
        TextView tvNumberPhotos = (TextView) eventNumPhotos_1.findViewById(R.id.vh_fragevent_tv_numberpictures);
        tvNumberPhotos.setText("1");
        mPhotosLayout.addView(eventNumPhotos_1);
    }

不幸的是,没有静态 XML 就无法绑定。您可以为要更新的每个视图设置 LiveDataObservableField

Android - Can I Databinding programatically? - without layout XML