搞定Android Agera-04

Agera更新了,加入了RecycleView DataBinding的支持,先睹为快:

布局文件

<layout xmlns:android="http://schemas.android.com/apk/res/android">
  <data>
    <variable name="note" type="Note"/>
    <variable name="click" type="Receiver"/>
    <variable name="longClick" type="Predicate"/>
  </data>
  <TextView ... android:onClick="@{() -> click.accept(note)}"
      android:onLongClick="@{() -> longClick.apply(note)}"
      android:text="@{note.note}"/>
</layout>

dataBindingRepositoryPresenter

配合RepositoryAdapter使用,创建dataBindingRepositoryPresenter

RepositoryAdapter adapter = repositoryAdapter()
  .add(notesStore.getNotesRepository(), dataBindingRepositoryPresenterOf(Note.class)
      .layout(R.layout.text_layout)
      .itemId(BR.note)
      .handler(BR.click,
          (Receiver<Note>) note -> {
              ...;
          })
      .handler(BR.longClick,
          (Predicate<Note>) notesStore::deleteNote)
      .forList())
  .build();

// Setup the recycler view using the repository adapter
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.result);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));

比较难理解的部分

.itemId(BR.note)创建了一个staticFunction(),用来提供BR.id
然后和data绑定
viewDataBinding.setVariable(itemId.apply(item), item);

  @Override
  public final void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
    ...
    presenters[resolvedRepositoryIndex].bind(
        data[resolvedRepositoryIndex], resolvedItemIndex, holder);
  }


    @Override
    public void bind(@NonNull final Object item, @NonNull final View view) {
      final ViewDataBinding viewDataBinding = DataBindingUtil.bind(view);
      viewDataBinding.setVariable(itemId.apply(item), item);
      for (final Pair<Integer, Object> handler : handlers) {
        viewDataBinding.setVariable(handler.first, handler.second);
      }
      viewDataBinding.executePendingBindings();
    }

Agera对RecycleView的支持还太弱

如果只是展示一个固定的列表,每次都整体更新,那么可以使用:

  /**
   * Invalidates the data set so {@link RecyclerView} will schedule a rebind of all data.
   */
  @Override
  public final void update() {
    dataInvalid = true;
    notifyDataSetChanged();
  }

GitHub地址

AndroidAgeraTutorial

发表评论

电子邮件地址不会被公开。 必填项已用*标注