Android convertView 正确处理

Android convertView proper handling

我的 android 项目中有以下 getView 的覆盖:

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
     DrawerListItemBinding binding;

     if (convertView == null) {
         binding = DataBindingUtil.inflate(
                 LayoutInflater.from(this.context),
                 R.layout.drawer_list_item, parent, false);
        if (binding == null) { return convertView; }
         binding.setTitle(values[position]);
         convertView = binding.getRoot();
     } else {
         binding = (DrawerListItemBinding) convertView.getTag();
     }

     if (binding == null) {
         return convertView;
     }
     binding.setIsCurrentView(activeIndex == position ? true : false);

     return convertView;

我不认为第二个空检查 binding==null 是正确的,因为我认为在那种情况下我需要 inflate/create 从头开始​​的新视图。我想知道 convertView 是否为非 null 但在使用 getTag() 转换为正确类型后它是 null 的条件是什么,如果是这种情况,最佳做法是什么......例如通过调用 DataBindingUtil.inflate()?

创建正确的视图

文档指出应该确保 convertView 不为 null 并且 "of the right type"。是指第二次空检查会命中的情况吗?

所以我在这里混淆了一些不同的东西。在文档中说 "Note: You should check that this view is non-null and of an appropriate type before using. If it is not possible to convert this view to display the correct data, this method can create a new view. "

第二个条件仅适用于使用异构列表的情况。由于这个特定问题没有,因此我不需要担心转换视图是否能够转换为适当的视图以显示正确的数据。两个 .getTag() 返回 null 因为它不是首先设置的。这可以通过简单地使用生成的数据绑定 class 类型安全 .bind(View root) 方法来解决,而不是从标签中获取绑定,如下所示:

  @Override
 public View getView(int position, View convertView, ViewGroup parent) {
 DrawerListItemBinding binding;

 if (convertView == null) {
     binding = DataBindingUtil.inflate(
             LayoutInflater.from(this.context),
             R.layout.drawer_list_item, parent, false);
     convertView = binding.getRoot();
 } else {
     binding = DrawerListItemBinding.bind(convertView);
 }

 binding.setTitle(values[position]);
 binding.setIsCurrentView(activeIndex == position ? true : false);

 return convertView;
}