2

how to use view binding in android list view? I know how to use it in Recycler View, but don't know how to use it in list view

6
  • 1
    why even use a listview then ? Sep 22, 2021 at 11:32
  • that's probably not an answer
    – Talha
    Sep 22, 2021 at 11:49
  • well, i didn't write it as an answer, i wrote it as a comment :) and i'm asking because list views are deprecated so why bother learning how to do it Sep 22, 2021 at 11:52
  • @a_local_nobody only use case for list view that I'm aware of is that they're supported by RemoteViews
    – Pawel
    Sep 22, 2021 at 11:56
  • @Pawel and i think widgets, perhaps ? Sep 22, 2021 at 12:04

1 Answer 1

3

Since list view provides raw views instead of viewholders you have to use another way to hold viewbinding, for example you can use view tags.

Create new ID in any of your resource files (like values.xml):

<id name="viewBinding" />

Then spawn view binding in your adapter (modified sample from docs):

private class MyAdapter extends BaseAdapter {

      // override other abstract methods here

      @Override
      public View getView(int position, View convertView, ViewGroup container) {
          ItemViewBinding binding;
          if (convertView == null) {
              binding = ItemViewBinding.inflate(getLayoutInflater(), container, false);
              convertView = binding.getRoot();
              convertView.setTag(R.id.viewBinding, binding);
          } else {
              binding = ((ItemViewBinding ) convertView.getTag(R.id.viewBinding));
          }
          
          binding.getText1().setText(getItem(position));

          return convertView;
      }
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.