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

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

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

14 条评论

  1. <a href="http://www.taxinowapp.com/wie-man-blumen-kleid-tr%C3%A4gt-dresse">wie man blumen kleid tr盲gt</a> <a href="http://www.billingaco.com/air-jordan-1-armada-amarillo-footi">air jordan 1 armada amarillo</a> <a href="http://www.ovioscope.com/nike-zoom-winflo-3-kvinders-r%C3%B8d-lyser%C3%B8d-butyg">nike zoom winflo 3 kvinders r酶d lyser酶d</a> <a href="http://www.judygeitzen.com/parajumpers-vest-etiquette-leaving-parajumpersb">parajumpers vest etiquette leaving</a> <a href="http://www.bentwoodridge.com/canada-goose-hybridge-hoody-womens-basket-canadagooseb">canada goose hybridge hoody womens basket</a> <a href="http://www.dallasjudaica.com/kyrie-1-bhm-xdr-kaufen-kurpesk">kyrie 1 bhm xdr kaufen</a>
    valomak http://www.valomak.com/

  2. <a href="http://www.tasdizayni.com/canada-goose-citadel-parka-sverige-quiz-canadagoosea">canada goose citadel parka sverige quiz</a> <a href="http://www.blogtourney.com/asics-gel-noosa-tri-8-rosso-rosa-kurpese">asics gel noosa tri 8 rosso rosa</a> <a href="http://www.edgethrive.com/adidas-zx-700-violet-jaune-kit-kurpesa">adidas zx 700 violet jaune kit</a> <a href="http://www.kewauneecares.com/nike-kevin-zeitler-mens-black-elite-jersey-68-nfl-home-cincinnati-bengals-nflt">nike kevin zeitler mens black elite jersey 68 nfl home cincinnati bengals</a> <a href="http://www.resekipman.com/billig-nike-air-speed-turf-menns-gr%C3%A5-footg">billig nike air speed turf menns gr氓</a> <a href="http://www.robineliza.com/nike-hyperdunk-2014-femminile-blu-oro-chaussuresd">nike hyperdunk 2014 femminile blu oro</a>
    zgzllc http://www.zgzllc.com/

  3. <a href="http://www.jlredcross.com/black-fendi-college-belt-beltr">black fendi college belt</a> <a href="http://www.nownessninja.com/mackage-jacket-sale-montreal-phone-number-hours-mackagee">mackage jacket sale montreal phone number hours</a> <a href="http://www.tedsrcrepair.com/hermes-reversible-belt-hermesr">hermes reversible belt</a> <a href="http://www.zovailangnews.com/parajumpers-gobi-mens-parajumpersr">parajumpers gobi mens</a> <a href="http://www.garagesetcinc.com/air-jordan-4.5-marr%C3%B3n-rosado-obuvb">air jordan 4.5 marr贸n rosado</a> <a href="http://www.immoetvous.com/nike-air-max-2017-red-and-white-uniform-runningd">nike air max 2017 red and white uniform</a>
    isnowbot http://www.isnowbot.com/

  4. avatar allefuerbeate

    <a href="http://www.webbgiganten.com/nike-air-jordan-cp3.vi-chris-paul-metalleic-s%C3%B8lv-kobe-chaussuresd">nike air jordan cp3.vi chris paul metalleic s酶lv kobe</a> <a href="http://www.deaffireside.com/the-north-face-mens-nuptse-vest-sale-by-owner-northfaceg">the north face mens nuptse vest sale by owner</a> <a href="http://www.guesthousesas.com/limited-weston-richburg-san-francisco-49ers-mens-jersey-58-player-name-number-tank-top-nike-nfl-red-nflw">limited weston richburg san francisco 49ers mens jersey 58 player name number tank top nike nfl red</a> <a href="http://www.haceryeni.com/mens-nike-pittsburgh-steelers-7-ben-roethlisberger-elite-green-salute-to-service-nfl-jersey-nflz">mens nike pittsburgh steelers 7 ben roethlisberger elite green salute to service nfl jersey</a> <a href="http://www.lapcomit.com/nike-free-rn-shoes-womens-running-skog">nike free rn shoes womens running</a> <a href="http://www.lebosmartlipo.com/jordan-retro-9-negro-rojo-gris-chaussuresg">jordan retro 9 negro rojo gris</a>
    allefuerbeate http://www.allefuerbeate.com/

  5. avatar dublinraces

    <a href="http://www.xzibitmalta.com/air-jordan-9-retro-bianca-nero-true-rosso-up-trainersd">air jordan 9 retro bianca nero true rosso up</a> <a href="http://www.genericpreset.com/adidas-neo-raleigh-high-top-kvinners-sneaker-gallery-chaussuresm">adidas neo raleigh high top kvinners sneaker gallery</a> <a href="http://www.bootberlin.com/ralph-lauren-baby-oxford-shirt-yellow-poloa">ralph lauren baby oxford shirt yellow</a> <a href="http://www.diettucson.com/nike-mercurial-vapor-rosado-for-venta-scarpek">nike mercurial vapor rosado for venta</a> <a href="http://www.schockenkatz.com/unik-vintage-blomstret-kjole-dresse">unik vintage blomstret kjole</a> <a href="http://www.drrandtherapy.com/nike-hypervenom-ii-phantom-premium-indoor-soccer-s%C3%B8lv-orange-sort-footi">nike hypervenom ii phantom premium indoor soccer s酶lv orange sort</a>
    dublinraces http://www.dublinraces.com/

  6. avatar kainstory

    <a href="http://www.duranerdogan.com/herre-nike-free-run-4.0-gul-orange-obuvc">herre nike free run 4.0 gul orange</a> <a href="http://www.trionbrain.com/jordan-retro-12-sort-and-gr%C3%A5-chaussuresb">jordan retro 12 sort and gr氓</a> <a href="http://www.dcrcustoms.com/oakley-mars-sunglasses-hot-new-sunglassesb">oakley mars sunglasses hot new</a> <a href="http://www.leesgoedplus.com/new-balance-996-womens-grey-pink-shoesd">new balance 996 womens grey pink</a> <a href="http://www.bermudabrands.com/gold-green-womens-nike-flex-fury-shoes-runningf">gold green womens nike flex fury shoes</a> <a href="http://www.dentaleden.com/authentic-pandora-clip-charms-pandorar">authentic pandora clip charms</a>
    kainstory http://www.kainstory.com/

  7. avatar abiliator

    <a href="http://www.xzibitmalta.com/abiti-floreali-per-il-matrimonio-di-primavera-dresse">abiti floreali per il matrimonio di primavera</a> <a href="http://www.genericpreset.com/kobe-9-low-yeezy-blanco-footi">kobe 9 low yeezy blanco</a> <a href="http://www.bootberlin.com/under-armour-curry-one-rose-noir-butyg">under armour curry one rose noir</a> <a href="http://www.diettucson.com/parajumpers-musher-jacket-ladies-parajumpersb">parajumpers musher jacket ladies</a> <a href="http://www.schockenkatz.com/canada-goose-jacket-arctic-expedition-jacket-canadagooseb">canada goose jacket arctic expedition jacket</a> <a href="http://www.drrandtherapy.com/nike-lebron-rot-wei%C3%9F-kurpesk">nike lebron rot wei脽</a>
    abiliator http://www.abiliator.com/

  8. avatar broadbandgeek

    <a href="http://www.turkunluvideo.com/vestidos-florales-casuales-dresse">vestidos florales casuales</a> <a href="http://www.apcroadlink.com/womens-air-jordan-retro-12-blue-australia-footi">womens air jordan retro 12 blue australia</a> <a href="http://www.comapanetwork.com/new-blance-996-b%C3%B8rn-sort-butyg">new blance 996 b酶rn sort</a> <a href="http://www.kellarit.com/parajumpers-vest-homme-homme-parajumpersb">parajumpers vest homme homme</a> <a href="http://www.cgmprecast.com/canada-goose-citadel-parka-navy-mens-jackets-basketball-canadagooseb">canada goose citadel parka navy mens jackets basketball</a> <a href="http://www.eleonorahotel.com/roshe-run-ovo-hvit-kurpesk">roshe run ovo hvit</a>
    broadbandgeek http://www.broadbandgeek.com/

  9. avatar dhanakaryam

    <a href="http://www.jaramiel.com/salomon-fellraiser-svart-widow-kurpesd">salomon fellraiser svart widow</a> <a href="http://www.connectbsl.com/nike-kd-8-tout-noir-panthers-schuhed">nike kd 8 tout noir panthers</a> <a href="http://www.aradefemalhas.com/jordan-jumpman-team-1-r%C3%B8d-and-sort-kurpesf">jordan jumpman team 1 r酶d and sort</a> <a href="http://www.funyari.com/herren-nike-flynit-air-max-gr%C3%BCn-schwarz-obuva">herren nike flynit air max gr眉n schwarz</a> <a href="http://www.cubanosocial.com/jordan-3-blanco-cehombrest-outfit-obuvf">jordan 3 blanco cehombrest outfit</a> <a href="http://www.mrtuckshop.com/nike-air-force-1-mid-07-schwarz-and-gold-obuvf">nike air force 1 mid 07 schwarz and gold</a>
    dhanakaryam http://www.dhanakaryam.com/

  10. avatar imovieye

    <a href="http://www.eastyorkvet.net/air-huarache-violet-punch-schuhec">air huarache violet punch</a> <a href="http://www.ebonyeyes.net/new-balance-990-gr%C3%A5-lilla-butyg">new balance 990 gr氓 lilla</a> <a href="http://www.eclinxplus.net/nike-kobe-11-gelb-himmelblau-scarpec">nike kobe 11 gelb himmelblau</a> <a href="http://www.ectvnews.net/nike-air-max-tailwind-6-s%C3%B8lv-himmelbl%C3%A5-chaussuresf">nike air max tailwind 6 s酶lv himmelbl氓</a> <a href="http://www.em-dmkm.net/nike-dunk-sky-hi-wei%C3%9F-butya">nike dunk sky hi wei脽</a> <a href="http://www.emiscape.net/adidas-projoator-2014-mundial-schuhea">adidas projoator 2014 mundial</a>
    imovieye http://www.imovieye.net/

  11. 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/

  12. 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]

  13. 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/

  14. avatar 托运行李

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

欢迎留言




用户登录

sitemap