手机QQ的可折叠列表在分组往上滑动时是可以停靠在最上方的,android默认的列表并没有提供相关的功能,其实可以简单的实现下,就是放一个View在最上面,在合适的时候显示出来就行了。

public class ExExpandableListView extends FrameLayout implements
        OnScrollListener, OnClickListener {

    private ExpandableListView mList;

    public ExExpandableListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mList = new ExpandableListView(context, null);
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(-1, -1);
        mList.setLayoutParams(lp);
        mFixedHeader = new TextView(context);
        FrameLayout.LayoutParams lp1 = new FrameLayout.LayoutParams(-1,
                LayoutParams.WRAP_CONTENT);
        mFixedHeader.setLayoutParams(lp1);
        addView(mList);
        addView(mFixedHeader);

        mList.setOnScrollListener(this);
        mFixedHeader.setOnClickListener(this);
        
        mList.setFadingEdgeLength(0);
    }
    

    TextView mFixedHeader;
    

    public ExpandableListView getList() {
        return mList;
    }

    private int mCurrentGroup = -1;

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {

        if (mList == null || mList.getChildCount() <= 0) {
            return;
        }

        final long flatPos = mList.getExpandableListPosition(firstVisibleItem);
        final int groupPos = ExpandableListView.getPackedPositionGroup(flatPos);
        
        if(groupPos != mCurrentGroup){
            //只有在组改变时才去设置文字
            String text = mList.getExpandableListAdapter().getGroup(groupPos)
                    .toString();
            mFixedHeader.setText(text);
        }
        
        mCurrentGroup = groupPos;
        
        if (mList.isGroupExpanded(groupPos)) {
            if(mFixedHeader.getVisibility() != View.VISIBLE){
                mFixedHeader.setVisibility(View.VISIBLE);
            }
        } else {
            if(mFixedHeader.getVisibility() != View.GONE){
                mFixedHeader.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v == mFixedHeader) {
            mFixedHeader.setVisibility(View.GONE);
            mList.collapseGroup(mCurrentGroup);
            mList.setSelectedGroup(mCurrentGroup);
        }
    }

}

只是简单的使用一个TextView去显示组的文字,还有很多细节没有考虑,比如说QQ的列表是当下面的组靠近停靠的组时是把停靠的那个视图推上去的。

版权声明:本文为douzifly原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/douzifly/archive/2011/08/31/2161426.html