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

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

常见的标签显示,这里用的是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
看了本文是不是觉得很赞,那就赶紧点击下面按钮分享给身边的朋友吧!

15 条评论

  1. <a href="http://www.mandydugan.com/nike-air-max-2017-femminile-verde-scarpel">nike air max 2017 femminile verde</a> <a href="http://www.dxnkofe.com/nike-kobe-10-elite-grey-purple-shoesj">nike kobe 10 elite grey purple</a> <a href="http://www.yurasmirnov.com/nike-air-max-2017-kvinders-s%C3%B8lv-lilla-skoi">nike air max 2017 kvinders s酶lv lilla</a> <a href="http://www.blovese.com/adidas-neo-skate-nero-gituttio-scarpeq">adidas neo skate nero gituttio</a> <a href="http://www.ztsurfboards.com/nike-flyknit-lunar-3-white-silver-shoesj">nike flyknit lunar 3 white silver</a> <a href="http://www.visheshcap.com/michael-kors-saddle-crossbody-bag-mkh">michael kors saddle crossbody bag</a>
    vstsblog http://www.vstsblog.com/

  2. <a href="http://www.drnatarajan.com/nike-internationalist-dahommes-orange-kurpesb">nike internationalist dahommes orange</a> <a href="http://www.eysenreich.com/france-17-digne-blue-soccer-country-jersey-nflr">france 17 digne blue soccer country jersey</a> <a href="http://www.jobmetry.com/nike-air-max-90-essential-hvit-dam-butyg">nike air max 90 essential hvit dam</a> <a href="http://www.pugdogdev.com/nfl-javorius-allen-ash-37-baltimore-ravens-nike-one-color-t-shirt-nflx">nfl javorius allen ash 37 baltimore ravens nike one color t shirt</a> <a href="http://www.realtyindubai.com/limited-nike-black-womens-cam-newton-jersey-nfl-1-carolina-panthers-2016-salute-to-service-nflw">limited nike black womens cam newton jersey nfl 1 carolina panthers 2016 salute to service</a> <a href="http://www.safeonproject.com/nike-tanjun-p%C3%BArpura-blanco-chaussuresa">nike tanjun p煤rpura blanco</a>
    moxiepouch http://www.moxiepouch.com/

  3. <a href="http://www.ortzproducts.com/dam%C3%A4nner-nike-dunk-schwarz-grau-schuheh">dam盲nner nike dunk schwarz grau</a> <a href="http://www.cooterscamera.com/air-jordan-retro-11-kvinners-gr%C3%B8nn-gul-obuvj">air jordan retro 11 kvinners gr酶nn gul</a> <a href="http://www.marjalfun.com/nike-zoom-ascention-blu-cielo-blu-scarpek">nike zoom ascention blu cielo blu</a> <a href="http://www.alecsblog.com/nike-soccers-chaussures-vert-chaussuresh">nike soccers chaussures vert</a> <a href="http://www.troudumonde.com/prada-milano-dal-1913-purse-price-pradah">prada milano dal 1913 purse price</a> <a href="http://www.smilesdrdavid.com/jay-ajayi-miami-dolphins-jersey-nfli">jay ajayi miami dolphins jersey</a>
    alecsblog http://www.alecsblog.com/

  4. <a href="http://www.eastyorkvet.net/kyrie-2-gelb-gr%C3%BCn-mucus-scarpee">kyrie 2 gelb gr眉n mucus</a> <a href="http://www.ebonyeyes.net/air-jordan-2-tout-rouge-jaune-butye">air jordan 2 tout rouge jaune</a> <a href="http://www.eclinxplus.net/kd-trey-5-rosa-slip-butyf">kd trey 5 rosa slip</a> <a href="http://www.ectvnews.net/air-jordan-13-rouge-jeep-schuhea">air jordan 13 rouge jeep</a> <a href="http://www.em-dmkm.net/asics-gel-kayano-21-nero-femminile-tennis-chaussuresa">asics gel kayano 21 nero femminile tennis</a> <a href="http://www.emiscape.net/nike-free-5.0-kvinders-wide-obuva">nike free 5.0 kvinders wide</a>
    trailspotters http://www.trailspotters.net/

  5. avatar fullcountkbo

    <a href="http://www.eworklife.com/blue-grey-womens-new-balance-576-shoes-trainersa">blue grey womens new balance 576 shoes</a> <a href="http://www.fullcountkbo.com/nike-air-max-90-gul-lyser%C3%B8d-scarpec">nike air max 90 gul lyser酶d</a> <a href="http://www.shackofstones.com/nike-shox-deliver-maschio-rosso-nose-kurpesd">nike shox deliver maschio rosso nose</a> <a href="http://www.tamworthbacon.com/ray-ban-aviator-large-metal-rb3025-sunglasses-dimensions-sunglassesg">ray ban aviator large metal rb3025 sunglasses dimensions</a> <a href="http://www.dvmengineers.com/nike-womens-adarius-glanton-limited-red-jersey-tampa-bay-buccaneers-nfl-53-therma-long-sleeve-nflr">nike womens adarius glanton limited red jersey tampa bay buccaneers nfl 53 therma long sleeve</a> <a href="http://www.questoffine.com/nike-hyperdunk-high-gas-skoa">nike hyperdunk high gas</a>
    fullcountkbo http://www.fullcountkbo.com/

  6. avatar mipaneldecontrol

    <a href="http://www.drcooper.net/nike-lunarglide-8-azul-gris-negro-butye">nike lunarglide 8 azul gris negro</a> <a href="http://www.drinkableair.net/nike-kobe-11-kvinders-orange-gr%C3%B8n-obuvd">nike kobe 11 kvinders orange gr酶n</a>
    mipaneldecontrol http://www.mipaneldecontrol.net/

  7. avatar lroyroofing

    <a href="http://www.ictbel.com/nike-air-max-90-em-womens-orange-pink-runninge">nike air max 90 em womens orange pink</a> <a href="http://www.ioioland.com/nike-femme-blazer-mid-tutti-nero-schuhea">nike femme blazer mid tutti nero</a> <a href="http://www.sesliesenyurt.com/nike-dunk-violet-bleu-scarpeb">nike dunk violet bleu</a> <a href="http://www.wethinkjerky.com/womens-nike-air-max-bw-white-netherlands-shoeso">womens nike air max bw white netherlands</a> <a href="http://www.dadees.com/nike-lunarepic-low-flyknit-kvinders-s%C3%B8lv-gr%C3%B8n-kurpesc">nike lunarepic low flyknit kvinders s酶lv gr酶n</a> <a href="http://www.pickwickcrc.com/retro-shoes-meaning-zapatost">retro shoes meaning</a>
    lroyroofing http://www.lroyroofing.com/

  8. avatar joubertets

    <a href="http://www.rcnspecials.com/jordan-retro-13-tout-bleu-butya">jordan retro 13 tout bleu</a> <a href="http://www.aprancheta.com/nike-free-run-5.0-v2-arancia-nero-guy-obuvd">nike free run 5.0 v2 arancia nero guy</a> <a href="http://www.getleanlearn.com/kvinders-nike-free-run-3-mintgr%C3%B8n-scarpea">kvinders nike free run 3 mintgr酶n</a> <a href="http://www.hbshbuick.com/adidas-soccer-boots-ag-adizero-f50dragon-azul-scarpee">adidas soccer boots ag adizero f50dragon azul</a> <a href="http://www.hvactampafl.com/air-jordan-9-retro-hvid-sort-wolf-gr%C3%A5-obuvc">air jordan 9 retro hvid sort wolf gr氓</a> <a href="http://www.zinmanlaw.com/air-jordan-retro-11-zapatos-for-venta-scarpea">air jordan retro 11 zapatos for venta</a>
    joubertets http://www.joubertets.com/

  9. avatar ikkunatehdas

    <a href="http://www.castalresources.net/air-jordan-super-fly-iv-marr%C3%B3n-amarillo-obuva">air jordan super fly iv marr贸n amarillo</a> <a href="http://www.cattivacosmetics.net/asics-l%C3%B8b-sko-s%C3%B8lv-lilla-butyc">asics l酶b sko s酶lv lilla</a> <a href="http://www.causses.net/kd-7-lyser%C3%B8d-and-lilla-heart-scarpeb">kd 7 lyser酶d and lilla heart</a> <a href="http://www.cconmausa.net/nike-tiempo-legend-viola-arancia-kurpesf">nike tiempo legend viola arancia</a> <a href="http://www.centralplainslifts.net/flyknit-lunar-1-marine-multi-year-scarpea">flyknit lunar 1 marine multi year</a> <a href="http://www.chateaulalinde.net/nike-zoom-clear-out-gris-rose-obuvc">nike zoom clear out gris rose</a>
    ikkunatehdas http://www.ikkunatehdas.net/

  10. avatar lubimochka

    <a href="http://www.polyphonyma.com/air-max-97-gull-bullet-journal-schuhef">air max 97 gull bullet journal</a> <a href="http://www.shoeskiin.com/kvinders-nike-blazer-sort-and-hvid-kurpesc">kvinders nike blazer sort and hvid</a> <a href="http://www.bondhuberman.com/nike-dunk-enfants-chaussures-blanc-vert-obuvg">nike dunk enfants chaussures blanc vert</a> <a href="http://www.cbstriad.com/nike-kaishi-villain-r%C3%B8d-cross-scarped">nike kaishi villain r酶d cross</a> <a href="http://www.feriadejaen.com/herre-nike-air-max-87-sb-alle-orange-butya">herre nike air max 87 sb alle orange</a> <a href="http://www.gonencymm.com/jordan-4-blanco-cehombrest-celebrity-chaussurese">jordan 4 blanco cehombrest celebrity</a>
    lubimochka http://www.lubimochka.com/

  11. avatar kidtokidboise

    <a href="http://www.cheapcoatsfr.com/nike-air-max-95-svart-mono-prm-schuhea">nike air max 95 svart mono prm</a> <a href="http://www.mylinkstv.com/nike-free-run-2-gelb-himmelblau-scarpeb">nike free run 2 gelb himmelblau</a> <a href="http://www.phxfam.com/womens-nike-huarache-utility-black-denmark-shoeso">womens nike huarache utility black denmark</a> <a href="http://www.shanibazaar.com/nike-flyknit-lunar-1-m%C3%A6nd-r%C3%B8d-guld-kurpesb">nike flyknit lunar 1 m忙nd r酶d guld</a> <a href="http://www.imannequins.com/nike-air-max-95-le-toddlers-zapatost">nike air max 95 le toddlers</a> <a href="http://www.irentevent.com/girls-high-converse-shoesz">girls high converse</a>
    kidtokidboise http://www.kidtokidboise.com/

  12. avatar divyangmart

    <a href="http://www.eworklife.com/nike-free-run-5.0-dam%C3%A4nner-leopard-kurpesa">nike free run 5.0 dam盲nner leopard</a> <a href="http://www.fullcountkbo.com/adidas-climacool-ride-iv-blue-pink-sneakerb">adidas climacool ride iv blue pink</a> <a href="http://www.shackofstones.com/nike-mercurial-victory-black-yellow-shoesg">nike mercurial victory black yellow</a> <a href="http://www.tamworthbacon.com/anaheim-ducks-zephyr-hat-hats">anaheim ducks zephyr hat</a> <a href="http://www.dvmengineers.com/nike-air-max-tailwind-7-herren-orange-sneakerf">nike air max tailwind 7 herren orange</a> <a href="http://www.questoffine.com/nike-air-presto-skull-svart-hvit-obuvd">nike air presto skull svart hvit</a>
    divyangmart http://www.divyangmart.com/

  13. avatar madamevelvet

    <a href="http://www.totalterapi.com/adidas-zx-flux-zapatillas-negro-mettodasic-plata-mint-kurpesd">adidas zx flux zapatillas negro mettodasic plata mint</a> <a href="http://www.usstatebanks.com/nike-kyrie-3-tout-noir-obuvg">nike kyrie 3 tout noir</a> <a href="http://www.ceethebarber.com/jordan-flight-23-vert-orange-scarpee">jordan flight 23 vert orange</a> <a href="http://www.conradtillard.com/nike-zoom-pegasus-31-oro-cielo-azul-butya">nike zoom pegasus 31 oro cielo azul</a> <a href="http://www.freemoviesaz.com/air-jordan-10-retro-schwarz-wei%C3%9F-house-chaussuresf">air jordan 10 retro schwarz wei脽 house</a> <a href="http://www.incaradio.com/lebron-12-rosado-and-p%C3%BArpura-queen-butya">lebron 12 rosado and p煤rpura queen</a>
    [url=http://www.madamevelvet.com/]madamevelvet[/url]

  14. avatar billknorr

    <a href="http://www.myfaccia.com/north-face-wool-jacket-mens-northfacer">north face wool jacket mens</a> <a href="http://www.csatags.com/burberry-scarf-engraved-up-scarfc">burberry scarf engraved up</a> <a href="http://www.pythausa.com/gi%C3%A0y-adidas-eqt-support-adv-skot">gi脿y adidas eqt support adv</a> <a href="http://www.gogogeeky.com/burberry-cashmere-scarf-cost-kenya-scarfb">burberry cashmere scarf cost kenya</a> <a href="http://www.kalaycioto.com/nobis-heritage-grey-jeans-nobisa">nobis heritage grey jeans</a> <a href="http://www.cathyrogoff.com/moncler-puffer-coat-sale-monclerr">moncler puffer coat sale</a>
    billknorr http://www.billknorr.com/

  15. avatar 托运行李

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

欢迎留言




用户登录

sitemap