首页 > 解决方案 > 使用视图绑定,您可以为通用视图子类定义类型参数吗?

问题描述

Android Studio 3.6 中添加的视图绑定功能消除了对笨重findViewById机制的需求。

但是,如果我没记错的话,它还不支持为泛型声明类型参数的方式。

考虑以下视图类:

/**
 * Spinner that calls toString() on choices to represent them in the UI.
 */
public class Spinner<T> extends androidx.appcompat.widget.AppCompatSpinner {

    // ...

    private List<T> items;

    private int selectedItemIndex;

    public void setItems(List<T> items) {
        this.items = items;
    }

    public T getSelectedItem() {
        return items.get(selectedItemIndex);
    }

}

现在,如果我的代码包含以下内容:

List<Foobar> foobars = getFoobarListFromSomewhere();
views.foobarSpinner.setItems(foobars);

然后 Android Studio 将向我显示未经检查的警告,例如:

Unchecked call to 'setItems(Collection<T>)' as a member of raw type 'org.example.views.Spinner'

解决它的唯一方法似乎是添加//noinspection unchecked或强制view.foobarSpinner转换为具有正确参数化类型的另一个变量,这非常麻烦。

目前有没有更清洁的方法来解决这个问题?

标签: androidandroid-studioandroid-layout

解决方案


推荐阅读