吐槽--ExpandableListView

   需要把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 <T extends ListAdapter & Filterable>	

 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 variable
        mAdapter = adapter;
        
        if (adapter != null) {
            // Create the connector
            mConnector = new ExpandableListConnector(adapter);
        } else {
            mConnector = null;
        }
        
        // Link the ListView (superclass) to the expandable list data through the connector
        super.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使用了。

 希望此文对您有用!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值