2019独角兽企业重金招聘Python工程师标准>>>
需要把ExpandableListView的适配器(继承自BaseExpandableListAdapter)同时绑定到AutoCompleteTextView,实现搜索过滤功能。实现了接口Filterable,以为成功在即,既然编译抛错误
The generic method setAdapter(T) of type AutoCompleteTextView is not applicable for the arguments (MyExpandableListAdapter). The inferred type MyExpandableListAdapter is not a valid substitute for the bounded parameter
MyExpandableListAdapter未实现ListAdapter,跟进BaseExpandableListAdapter最终继承的接口ExpandableListAdapter既然不是ListAdapter的子类!ExpandableListView继承自ListView google既然让它实现不同的适配器,哦!狗屎!
继续看看setAdapter有两个重载
public void setAdapter(ExpandableListAdapter adapter)public void setAdapter(ListAdapter adapter)
如果调用
public void setAdapter(ListAdapter adapter)
直接就抛异常。看另外一个函数的实现
public void setAdapter(ExpandableListAdapter adapter) {// Set member variablemAdapter = adapter;if (adapter != null) {// Create the connectormConnector = new ExpandableListConnector(adapter);} else {mConnector = null;}// Link the ListView (superclass) to the expandable list data through the connectorsuper.setAdapter(mConnector);}
看,google既然在ExpandableListAdapter和ListAdapter直接做一个链接器来适配ListView。
ExpandableListView的这种实现方法,虽然可重用listview,但函数setAdapter签名和父类ListView不统一,无疑给调用者添加陷阱和增加复杂度。
回到上面的问题:如果需要MyExpandableListAdapter同时能够被AutoCompleteTextView做adapter,只好乖乖实现ListAdapter,所以要实现ListAdapter、ExpandableListAdapter两个接口。这么来编译还是不能通过。
For ExpandableListView, use setAdapter(ExpandableListAdapter) instead of " +"setAdapter(ListAdapter)
聪明的java编译器把MyExpandableListAdapter认为是ListAdapter的子类了。怎么办?很简单!一个小技巧让编译器更加聪明点
expandableListView.setAdapter((ExpandableListAdapter)MyExpandableListAdapter);
至此MyExpandableListAdapter就不仅可以被ExpandableListView使用而且可以被AutoCompleteTextView使用了。
希望此文对您有用!