标签控件 流式布局 实现单选 多选

单选效果图:


标签控件 流式布局 实现单选 多选_第1张图片
 以setAdapter形式注入数据

  mFlowLayout.setAdapter(new TagAdapter(mVals)
        {

            @Override
            public View getView(FlowLayout parent, int position, String s)
            {
                TextView tv = (TextView) mInflater.inflate(R.layout.tv, mFlowLayout, false);
                tv.setText(s);
                return tv;
            }
        });
  • 直接设置selector为background即可完成标签选则的切换,类似CheckBox
  • 支持控制选择的Tag数量,比如:单选
  支持setOnTagClickListener,当点击某个Tag回调

 mFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener()
        {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent)
            {
                Toast.makeText(getActivity(), mVals[position], Toast.LENGTH_SHORT).show();
                return true;
            }
        });

 支持setOnSelectListener,当选择某个Tag后回调
  mFlowLayout.setOnSelectListener(new TagFlowLayout.OnSelectListener()
        {
            @Override
            public void onSelected(Set selectPosSet)
            {
                getActivity().setTitle("choose:" + selectPosSet.toString());
            }
        });
  • 支持adapter.notifyDataChanged
  • Activity重建(或者旋转)后,选择的状态自动
  抽取了鸿洋大神的FlowLayout

  实现单选的核心代码:
    private void doSelect(TagView child, int position) {
        if (!child.isChecked()) {
            if (mSelectedView.size() == 1) {
                Iterator iterator = mSelectedView.iterator();
                Integer preIndex = iterator.next();
                TagView pre = (TagView) getChildAt(preIndex);
                setChildUnChecked(preIndex, pre);
                setChildChecked(position, child);

                mSelectedView.remove(preIndex);
                mSelectedView.add(position);
            } else {
                setChildChecked(position, child);
                mSelectedView.add(position);
            }
        } else {
            setChildUnChecked(position, child);
            mSelectedView.remove(position);
        }
        //处理max_select=1的情况

        if (mOnSelectListener != null) {
            mOnSelectListener.onSelected(new HashSet(mSelectedView));
        }
    }

使用 mSelectedView.add(position)对每一次选择的position进行保存,再次点击的时候,判断当mSelectedView.size() == 1的时候说明已经选择了一个,那么就通过遍历,把上次点击的position进行remov掉,add当前的position ;从而实现单选的原理

多选效果图:

标签控件 流式布局 实现单选 多选_第2张图片
核心代码:

private void doSelect(TagView child, int position) {
        if (!child.isChecked()) {
            setChildChecked(position, child);
            mSelectedView.add(position);
        } else {
            setChildUnChecked(position, child);
            mSelectedView.remove(position);
        }
        if (mOnSelectListener != null) {
            mOnSelectListener.onSelected(new HashSet(mSelectedView));
        }
    }


代码的下载地址
单选: http://download.csdn.net/download/jingerlovexiaojie/10189423
多选:http://download.csdn.net/download/jingerlovexiaojie/10190088

你可能感兴趣的:(Android)