Android自定義底部菜單欄控件

在App開發(fā)時(shí)經(jīng)常會遇到需要做類似微信底部切換按鈕那樣的菜單欄,所以封裝了一個底部菜單控件狐胎,方便日后使用涯鲁。
先看一下demo效果


先看如何進(jìn)行使用巷查,在看如何實(shí)現(xiàn)。
1抹腿、在activity_main.xml布局里引用控件

2岛请、在activity進(jìn)行設(shè)置數(shù)據(jù)

public class MainActivity extends AppCompatActivity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomMenuView bmv_list = (BottomMenuView) findViewById(R.id.bmv_list);
        //設(shè)置bottom數(shù)據(jù)
        bmv_list.setBottomItem(getData());
        //監(jiān)聽點(diǎn)擊事件
        bmv_list.setBottomItemOnClickListener(new BottomMenuView.BottomItemOnClickListener() {
            @Override
            public void bottomItemOnClick(View view, int i, BottomItem item) {
                Toast.makeText(getApplicationContext(),"點(diǎn)擊了第"+i+"個",Toast.LENGTH_SHORT).show();
            }
        });
        //默認(rèn)選擇第幾個
        bmv_list.setShowIndex(0);
    }
    /**
     * 創(chuàng)建bottom數(shù)據(jù)
     * @return
     */
    public List<BottomItem> getData(){
        List<BottomItem> items = new ArrayList<>();
        items.add(new BottomItem("首頁",R.mipmap.icon_function_tab));
        items.add(new BottomItem("信息",R.mipmap.icon_home_tab));
        items.add(new BottomItem("應(yīng)用",R.mipmap.icon_my_tab));
        items.add(new BottomItem("我的",R.mipmap.icon_home_tab));
        return items;
    }
}

Bottomitem的代碼

public class BottomItem {
    private String name;
    private int icon;
    public BottomItem(String name, int icon) {
        this.name = name;
        this.icon = icon;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public int getIcon() {
        return icon;
    }

    public void setIcon(int icon) {
        this.icon = icon;
    }
}

是不是很方便呢!

現(xiàn)在來BottomMenuView看看是怎么實(shí)現(xiàn)的

public class BottomMenuView extends LinearLayout implements View.OnClickListener{
    private static final String TAG = "BottomMenuView";
    private Context mContext;
    private int imgColor = 0xff009AFF;//點(diǎn)擊改變圖片顏色
    private int imgDefaultColor = 0xff565656;//默認(rèn)圖片顏色
    private float textSize = 12; //字體大小
    private int imgPadding = 12; //內(nèi)邊距
    private List<BottomItem> bottomItems;//Item列表
    private List<Button> buttons;//buttom列表
    private int width;
    private int hight;
    //回調(diào)接口
    private BottomItemOnClickListener bottomItemOnClickListener;
    public BottomMenuView(Context context) {
        super(context);
        initView(context);
    }
    public BottomMenuView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }
    public BottomMenuView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }
    public void initView(Context context){
        mContext =context;
        buttons = new ArrayList<>();//實(shí)例化按鈕列表
    }
    /**
     * 傳入item列表
     * @param bottomItems
     */
    public void setBottomItem(List<BottomItem> bottomItems){
        this.bottomItems = bottomItems;
        //循環(huán)button按鈕
        for (int i = 0; i < bottomItems.size(); i++) {
            //創(chuàng)建button
            Button buttom = new Button(mContext);
            //設(shè)置寬和高為MATCH_PARENT
            LayoutParams layoutParams = new LayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            buttom.setLayoutParams(layoutParams);
            //字體居中
            buttom.setGravity(Gravity.CENTER);
            //設(shè)置文字
            buttom.setText(bottomItems.get(i).getName());
            //設(shè)置文字大小
            buttom.setTextSize(textSize);
            //設(shè)置內(nèi)邊距
            buttom.setPadding(imgPadding,imgPadding,imgPadding,imgPadding);
            //去掉button背景
            buttom.setBackground(null);
            //獲取圖標(biāo)資源
            Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(),bottomItems.get(i).getIcon());
            //設(shè)置圖標(biāo)默認(rèn)顏色
            Drawable drawable = new BitmapDrawable(getResources(),tintBitmap(bitmap,imgDefaultColor));
            //設(shè)置圖標(biāo)
            buttom.setCompoundDrawablesWithIntrinsicBounds(null,drawable,null,null);
            //將item設(shè)置到tag中下一步需要用到
            buttom.setTag(bottomItems.get(i));
            //設(shè)置監(jiān)聽
            buttom.setOnClickListener(this);
            //添加到當(dāng)前布局
            addView(buttom);
            //添加到按鈕組里
            buttons.add(buttom);
        }
    }
    private boolean isShow = false;
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        //計(jì)算每一個子button的寬度 并且判斷只計(jì)算一次
        if (!isShow){
            for (int i = 0; i < getChildCount(); i++) {
                LinearLayout.LayoutParams ll = (LayoutParams) getChildAt(i).getLayoutParams();
                ll.width=width/bottomItems.size();
                getChildAt(i).setLayoutParams(ll);
            }
            isShow=true;
        }
    }
    /**
     * 手動設(shè)置選中的button
    **/
    public void setShowIndex(int index){
        if (buttons.size()!=0){
            BottomItem bottomItem = (BottomItem) buttons.get(index).getTag();
            getBitmap(buttons.get(index),bottomItem.getIcon(),imgColor);
            bottomItemOnClickListener.bottomItemOnClick(buttons.get(index),index,bottomItem);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width = MeasureSpec.getSize(widthMeasureSpec);
        hight = MeasureSpec.getSize(heightMeasureSpec);
    }

    /**
     * 改變選中顏色
     * @param btn
     * @param img
     * @param color
     */
    public void getBitmap(Button btn, int img, int color){
        btn.setTextColor(color);
        Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(),img);
        Drawable drawable = new BitmapDrawable(mContext.getResources(), tintBitmap(bitmap,color));
        btn.setCompoundDrawablesWithIntrinsicBounds(null,drawable,null,null);
    }

    /**
     * 對每一個BUTTON進(jìn)行監(jiān)聽
     * @param view
     */
    @Override
    public void onClick(View view) {
        for (int i = 0; i < buttons.size(); i++) {
            BottomItem bottomItem = (BottomItem) buttons.get(i).getTag();//從tag中獲取BottomItem
            getBitmap(buttons.get(i),bottomItem.getIcon(),imgDefaultColor);//重置按鈕顏色
            if (buttons.get(i).getTag()==view.getTag()){//判斷點(diǎn)擊的是哪個按鈕
                getBitmap(buttons.get(i),bottomItem.getIcon(),imgColor);//更改被點(diǎn)擊的按鈕牙
                if (bottomItemOnClickListener != null) {
                    //通知回調(diào)
                    bottomItemOnClickListener.bottomItemOnClick(view,i,bottomItem);
                }
            }
        }

    }
    public BottomItemOnClickListener getBottomItemOnClickListener() {
        return bottomItemOnClickListener;
    }
    
    public void setBottomItemOnClickListener(BottomItemOnClickListener bottomItemOnClickListener) {
        this.bottomItemOnClickListener = bottomItemOnClickListener;
    }
    /**
     * 點(diǎn)擊監(jiān)聽回調(diào)接口
     */
    public interface BottomItemOnClickListener{
        void bottomItemOnClick(View view, int i,BottomItem item);
    }
    /**
     * 改變顏色
     * @param inBitmap
     * @param tintColor
     * @return
     */
    public static Bitmap tintBitmap(Bitmap inBitmap , int tintColor) {
        if (inBitmap == null) {
            return null;
        }
        Bitmap outBitmap = Bitmap.createBitmap (inBitmap.getWidth(), inBitmap.getHeight() , inBitmap.getConfig());
        Canvas canvas = new Canvas(outBitmap);
        Paint paint = new Paint();
        paint.setColorFilter( new PorterDuffColorFilter(tintColor, PorterDuff.Mode.SRC_IN)) ;
        canvas.drawBitmap(inBitmap , 0, 0, paint) ;
        return outBitmap ;
    }

    /**  get / set **/
    public int getImgDefaultColor() {
        return imgDefaultColor;
    }

    public void setImgDefaultColor(int imgDefaultColor) {
        this.imgDefaultColor = imgDefaultColor;
    }

    public int getImgColor() {
        return imgColor;
    }

    public void setImgColor(int imgColor) {
        this.imgColor = imgColor;
    }

    public float getTextSize() {
        return textSize;
    }

    public void setTextSize(float textSize) {
        this.textSize = textSize;
    }

    public int getImgPadding() {
        return imgPadding;
    }

    public void setImgPadding(int imgPadding) {
        this.imgPadding = imgPadding;
    }
}

代碼比較簡單警绩,相信大家看一遍都可以理解崇败。
全部代碼已托管到開源中國的碼云和GitHub上,歡迎下載。
地址:
https://github.com/yancy2430/BottomNavView
https://git.oschina.net/zhe2430/BottomNavView
也可以直接Gradle引用

compile 'com.tdeado:bottomnav:1.0.0'

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末后室,一起剝皮案震驚了整個濱河市缩膝,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌岸霹,老刑警劉巖疾层,帶你破解...
    沈念sama閱讀 218,122評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異松申,居然都是意外死亡云芦,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評論 3 395
  • 文/潘曉璐 我一進(jìn)店門贸桶,熙熙樓的掌柜王于貴愁眉苦臉地迎上來舅逸,“玉大人,你說我怎么就攤上這事皇筛×鹄” “怎么了?”我有些...
    開封第一講書人閱讀 164,491評論 0 354
  • 文/不壞的土叔 我叫張陵水醋,是天一觀的道長旗笔。 經(jīng)常有香客問我,道長拄踪,這世上最難降的妖魔是什么蝇恶? 我笑而不...
    開封第一講書人閱讀 58,636評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮惶桐,結(jié)果婚禮上撮弧,老公的妹妹穿的比我還像新娘。我一直安慰自己姚糊,他們只是感情好贿衍,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,676評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著救恨,像睡著了一般贸辈。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上肠槽,一...
    開封第一講書人閱讀 51,541評論 1 305
  • 那天擎淤,我揣著相機(jī)與錄音,去河邊找鬼秸仙。 笑死揉燃,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的筋栋。 我是一名探鬼主播,決...
    沈念sama閱讀 40,292評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼正驻,長吁一口氣:“原來是場噩夢啊……” “哼弊攘!你這毒婦竟也來了抢腐?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,211評論 0 276
  • 序言:老撾萬榮一對情侶失蹤襟交,失蹤者是張志新(化名)和其女友劉穎迈倍,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體捣域,經(jīng)...
    沈念sama閱讀 45,655評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡啼染,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,846評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了焕梅。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片迹鹅。...
    茶點(diǎn)故事閱讀 39,965評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖贞言,靈堂內(nèi)的尸體忽然破棺而出斜棚,到底是詐尸還是另有隱情,我是刑警寧澤该窗,帶...
    沈念sama閱讀 35,684評論 5 347
  • 正文 年R本政府宣布弟蚀,位于F島的核電站,受9級特大地震影響酗失,放射性物質(zhì)發(fā)生泄漏义钉。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,295評論 3 329
  • 文/蒙蒙 一规肴、第九天 我趴在偏房一處隱蔽的房頂上張望捶闸。 院中可真熱鬧,春花似錦奏纪、人聲如沸鉴嗤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,894評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽醉锅。三九已至,卻和暖如春发绢,著一層夾襖步出監(jiān)牢的瞬間硬耍,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,012評論 1 269
  • 我被黑心中介騙來泰國打工边酒, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留经柴,地道東北人。 一個月前我還...
    沈念sama閱讀 48,126評論 3 370
  • 正文 我出身青樓墩朦,卻偏偏與公主長得像坯认,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,914評論 2 355

推薦閱讀更多精彩內(nèi)容