How to use Viewbinding in Android Java ListView

Issue

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

Solution

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;
      }
  }

Answered By – Pawel

Leave a Comment