android:用ToggleButton实现标签显示效果

2015年11月15日 Android 4条评论 阅读5226次

常见的标签显示,这里用的是ToggleButton加上自定义ViewGroup改装的。

效果是这样子的(分别显示了标签通常状态和被选择状态的样子)

device-2015-11-10-105635.png



public class TagsAdapter extends BaseAdapter {
    private List<String> mList;
    private LayoutInflater mInflater;
    public TagsAdapter(Context context, List<String> list) {
        if (list == null) {
            mList = new ArrayList<String>();
        } else {
            mList = list;
        }
        mInflater = LayoutInflater.from(context);
    }
    @Override
    public int getCount() {
        return mList.size();
    }
    @Override
    public String getItem(int position) {
        return mList.get(position);
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final String text = getItem(position);
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.tags_item, null);
            holder = new ViewHolder();
            holder.tagBtn = (ToggleButton) convertView
                    .findViewById(R.id.tag_btn);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.tagBtn.setText(text);
        holder.tagBtn.setTextOff(text);
        holder.tagBtn.setTextOn(text);
        return holder.tagBtn;
    }
    static class ViewHolder {
        ToggleButton tagBtn;
    }
}




public class TagLayout extends ViewGroup {
    private static final int LINE_SPACE = 10;
    private static final int TAG_SPACE = 15;
    private int mLineSpacing;
    private int mTagSpacing;
    private BaseAdapter mAdapter;
    private TagItemClickListener mListener;
    private DataChangeObserver mObserver;
    public TagLayout(Context context) {
        super(context);
        init(context, null, 0);
    }
    public TagLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }
    public TagLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }
    private void init(Context context, AttributeSet attrs, int defStyle) {
        mLineSpacing = LINE_SPACE;
        mTagSpacing = TAG_SPACE;
    }
    private void drawLayout() {
        if (mAdapter == null/* || mAdapter.getCount() == 0 */) {
            return;
        }
        this.removeAllViews();
        for (int i = 0, count = mAdapter.getCount(); i < count; i++) {
            View view = mAdapter.getView(i, null, null);
            final int position = i;
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mListener != null) {
                        mListener.itemClick(position);
                    }
                }
            });
            this.addView(view);
        }
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int wantHeight = 0;
        int wantWidth = resolveSize(0, widthMeasureSpec);
        int paddingLeft = getPaddingLeft();
        int paddingRight = getPaddingRight();
        int paddingTop = getPaddingTop();
        int paddingBottom = getPaddingBottom();
        int childLeft = paddingLeft;
        int childTop = paddingTop;
        int lineHeight = 0;
        LayoutParams params;
        for (int i = 0, count = getChildCount(); i < count; i++) {
            final View childView = getChildAt(i);
            params = childView.getLayoutParams();
            childView.measure(
                    getChildMeasureSpec(widthMeasureSpec, paddingLeft
                            + paddingRight, params.width),
                    getChildMeasureSpec(heightMeasureSpec, paddingTop
                            + paddingBottom, params.height));
            int childHeight = childView.getMeasuredHeight();
            int childWidth = childView.getMeasuredWidth();
            lineHeight = Math.max(childHeight, lineHeight);
            if (childLeft + childWidth + paddingRight > wantWidth) {
                childLeft = paddingLeft;
                childTop += mLineSpacing + childHeight;
                lineHeight = childHeight;
            }
            childLeft += childWidth + mTagSpacing;
        }
        wantHeight += childTop + lineHeight + paddingBottom;
        setMeasuredDimension(wantWidth,
                resolveSize(wantHeight, heightMeasureSpec));
    }
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int width = r - l;
        int paddingLeft = getPaddingLeft();
        int paddingTop = getPaddingTop();
        int paddingRight = getPaddingRight();
        int childLeft = paddingLeft;
        int childTop = paddingTop;
        int lineHeight = 0;
        for (int i = 0, count = getChildCount(); i < count; i++) {
            final View childView = getChildAt(i);
            if (childView.getVisibility() == View.GONE) {
                continue;
            }
            int childWidth = childView.getMeasuredWidth();
            int childHeight = childView.getMeasuredHeight();
            lineHeight = Math.max(childHeight, lineHeight);
            if (childLeft + childWidth + paddingRight > width) {
                childLeft = paddingLeft;
                childTop += mLineSpacing + lineHeight;
                lineHeight = childHeight;
            }
            childView.layout(childLeft, childTop, childLeft + childWidth,
                    childTop + childHeight);
            childLeft += childWidth + mTagSpacing;
        }
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new LayoutParams(this.getContext(), attrs);
    }
    public void setAdapter(BaseAdapter adapter) {
        if (mAdapter == null) {
            mAdapter = adapter;
            if (mObserver == null) {
                mObserver = new DataChangeObserver();
                mAdapter.registerDataSetObserver(mObserver);
            }
            drawLayout();
        }
    }
    public void setItemClickListener(TagItemClickListener mListener) {
        this.mListener = mListener;
    }
    public interface TagItemClickListener {
        void itemClick(int position);
    }
    class DataChangeObserver extends DataSetObserver {
        @Override
        public void onChanged() {
            TagLayout.this.drawLayout();
        }
        @Override
        public void onInvalidated() {
            super.onInvalidated();
        }
    }
}



<?xml version="1.0" encoding="utf-8"?>
<ToggleButton xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tag_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/tag_bg"
    android:gravity="center"
    android:textSize="16sp" >
</ToggleButton>



核心代码基本就这些了。
下载工程完整代码请到github
github地址为:
https://github.com/will86/TagLayout


分享本文至:

WRITTEN BY

avatar
看了本文是不是觉得很赞,那就赶紧点击下面按钮分享给身边的朋友吧!

4 条评论

  1. avatar mybigrefund

    <a href="http://www.leatheroneph.com/nike-stefan-janoski-max-negro-verde-zapatosk">nike stefan janoski max negro verde</a> <a href="http://www.massageturkey.com/dam%C3%A4nner-adidas-gazelle-boost-blau-runningc">dam盲nner adidas gazelle boost blau</a> <a href="http://www.codeconuts.com/adidas-baby-azul-stan-smith-zapatosj">adidas baby azul stan smith</a> <a href="http://www.radiationism.com/kvinners-nike-flyknit-lunar-3-gr%C3%B8nn-rosa-chaussuresa">kvinners nike flyknit lunar 3 gr酶nn rosa</a> <a href="http://www.chessarbiters.com/nike-roshe-run-team-r%C3%B8d-and-sail-foota">nike roshe run team r酶d and sail</a> <a href="http://www.varisofttech.com/kd-7-fireworks-for-venta-runningd">kd 7 fireworks for venta</a>
    mybigrefund http://www.mybigrefund.com/

  2. avatar estilomusic

    <a href="http://www.livyourdreamz.com/ralph-lauren-noir-bag-polou">ralph lauren noir bag</a> <a href="http://www.mailstraight.com/nike-roshe-run-olive-gr%C3%BCn-xanax-chaussuresa">nike roshe run olive gr眉n xanax</a> <a href="http://www.mozhizhou.com/nike-zoom-pegasus-34-for-vente-pa-schuhed">nike zoom pegasus 34 for vente pa</a> <a href="http://www.nicholaslars.com/air-yeezy-ii-2-sp-max-90-kvinders-sort-bl%C3%A5-scarpea">air yeezy ii 2 sp max 90 kvinders sort bl氓</a> <a href="http://www.phihochdrei.com/air-jordan-after-game-guld-orange-kurpesf">air jordan after game guld orange</a> <a href="http://www.saintcroyheet.com/elite-mens-sammie-coates-navy-blue-jersey-nfl-nike-houston-texans-18-rush-vapor-untouchable-nflr">elite mens sammie coates navy blue jersey nfl nike houston texans 18 rush vapor untouchable</a>
    [url=http://www.estilomusic.com/]estilomusic[/url]

  3. avatar poppiesdelray

    <a href="http://www.forttr.com/adidas-zx-flux-gul-skoh">adidas zx flux gul</a> <a href="http://www.chopkinslaw.com/majestic-new-york-yankees-maillot-de-baseball-long-en-jersey-nfli">majestic new york yankees maillot de baseball long en jersey</a> <a href="http://www.plusbolivia.com/converse-r%C3%B8d-high-tops-menn-obuvk">converse r酶d high tops menn</a> <a href="http://www.ahlivv.com/coach-bags-on-sale-outlet-coachh">coach bags on sale outlet</a> <a href="http://www.bybrettbarner.com/nike-air-max-90-maschio-obsidian-bianca-scarpej">nike air max 90 maschio obsidian bianca</a> <a href="http://www.timowallets.com/a-buon-mercato-rosa-converse-scarpe-scarpei">a buon mercato rosa converse scarpe</a>
    poppiesdelray http://www.poppiesdelray.com/

  4. avatar 托运行李

    面对如此深奥的数字 嘿嘿   不懂

欢迎留言




用户登录

sitemap