textview实现底部栏图文效果

textview实现底部栏图文效果

以前写底部栏的总是习惯用textview+imageview这种写法实现,发现每次写代码麻烦,还需要在最外面添加一层布局嵌套,当然这样一嵌套层级增加,布局就影响到了性能。我可不想因为这小小的地方造成代码的冗余和apk的内存增加太多。然后在网上搜索了一番,在掘金上发现一个类似的,但是运行后不是自己想要的结果。
先声明我用的Hyman大神的auto适配库,所以代码都会和auto库结合,当然也有不用这个库的代码编写,如果你还不知道auto库,那么戳(戳戳戳戳戳戳)这里吧!!!

效果如下图,很丑


这里写图片描述

后来经过其他的帮助,修改出了适合自己项目用的效果代码。废话少说,代码来了。

  1. attrs.xml文件
 <declare-styleable name="itb">
        <attr name="img" format="reference" />
        <attr name="text" format="string|reference"></attr>
        <attr name="text_size" format="integer|reference"></attr>
        <attr name="img_width" format="dimension|reference"></attr>
        <attr name="img_height" format="dimension|reference"></attr>
        <attr name="margin_top" format="dimension|reference"></attr>
        <attr name="text_margin_bottom" format="dimension|reference"></attr>
        <attr name="text_color" format="color|reference"></attr>
        <attr name="margin_bottom" format="dimension|reference"></attr>
    </declare-styleable>

属性定义,这个就不用说了

2.自定义代码

package com.hangzhou.bijianhuzhu.customView;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hangzhou.bijianhuzhu.bjhz.R;
import com.hangzhou.bijianhuzhu.tools.ImageUtil;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.utils.AutoUtils;

/**
 * 设置TextView drawable图片大小 图片距离文字的大小
 * Created by  chunfu on 2016/11/9.
 */

public class RichText  extends AutoLinearLayout {

    private Context context;

    private View mRoot = null;
    private ImageView mImgView = null;
    private TextView mTextView = null;
    private Drawable mImg;//图片资源
    private String mText;//文字内容
    private float mTextSize;
    private float width;
    private float height;
    private int mImgWidth;
    private int mImgHeigh;

    private float marginTop;
    private float textMarginbottom;
    private float marginBottom;

    private static int TEXT_MARGIN_BOTTOM = 5;
    private static int MARGIN_TOP = 8;
    private static int MARGIN_BOTTOM = 3;
    private static int IMAGE_WIDTH = 18;
    private static int IMAGE_HEIGHT = 18;// px像素值
    private static int TEXT_SIZE = 15;

    int textColor;

    public RichText(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.itb);
        mImg = ta.getDrawable(R.styleable.itb_img);
        mText = ta.getString(R.styleable.itb_text);

//        resetSize();

        mTextSize = ta.getFloat(R.styleable.itb_text_size, TEXT_SIZE);
        width = ta.getDimension(R.styleable.itb_img_width, IMAGE_WIDTH);

        height = ta.getDimension(R.styleable.itb_img_height, IMAGE_HEIGHT);
        marginTop = ta.getDimension(R.styleable.itb_margin_top, MARGIN_TOP);
        textMarginbottom = ta.getDimension(R.styleable.itb_text_margin_bottom,
                TEXT_MARGIN_BOTTOM);
        marginBottom = ta.getDimension(R.styleable.itb_margin_bottom, MARGIN_BOTTOM);
        textColor = ta.getColor(R.styleable.itb_text_color, 0xff333333);


        // TODO: 2016/11/9  实现效果适配需要放开下面的代码 
//        width = AutoUtils.getPercentWidthSize((int) width);
//        height = AutoUtils.getPercentWidthSize((int) height);
//        marginTop= AutoUtils.getPercentWidthSize((int)marginTop);

        if (width == IMAGE_WIDTH) {
            resetSize();
        }

        initView();
        // 及时回收资源(一定需要,防止OOM)
        ta.recycle();
    }
    /**
     * 重新设置大小
     *
     */
    private void resetSize() {
        width = dip2px(context, width);
        height = dip2px(context, height);
        marginTop = dip2px(context, marginTop);
        textMarginbottom = dip2px(context, textMarginbottom);
        marginBottom = dip2px(context, marginBottom);
    }
    /**
     * 初始化控件
     *
     */
    private void initView() {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mRoot = inflater.inflate(R.layout.view_imagetext, this, true);

        mImgView = (ImageView) mRoot.findViewById(R.id.img);
        mTextView = (TextView) mRoot.findViewById(R.id.txt);
        if (textMarginbottom != TEXT_MARGIN_BOTTOM) {
            LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            params.setMargins(0, 0, 0, (int) textMarginbottom);
            mTextView.setLayoutParams(params);
        }

        setImageSize();

        mTextView.setText(mText);
        mTextView.setTextSize(mTextSize);
        mTextView.setTextColor(textColor);
    }
   /**
     * 设置图片size大小
     *
     */
    private void setImageSize() {
        mImgWidth = mImg.getIntrinsicWidth();
        mImgHeigh = mImg.getIntrinsicHeight();

        if (width * mImgHeigh > height * mImgWidth) {
            LayoutParams params = new LayoutParams(
                    (int) (mImgWidth * height / mImgHeigh), (int) (mImgHeigh
                    * height / mImgHeigh));
            params.setMargins(0, (int) marginTop, 0, (int) marginBottom);
            mImgView.setLayoutParams(params);
        } else {
            LayoutParams params = new LayoutParams(
                    (int) (mImgWidth * width / mImgWidth), (int) (mImgHeigh
                    * width / mImgWidth));
            params.setMargins(0, (int) marginTop, 0, (int) marginBottom);
            mImgView.setLayoutParams(params);
        }

        ImageUtil.setBackgroundInDrawable(mImgView, mImg);
    }

    /**
     * 设置背景图片
     *
     * @param resId
     * @param text
     */
    public void setImageViewBackground(int resId, String text) {
        mImg = context.getResources().getDrawable(resId);
        setImageSize();
        mTextView.setText(text);
    }

    /**
     * @param context 上下文
     * @param dpValue 手机分辨率
     * @return
     * @Title: dip2px
     * @Description: 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     * @author Linlj
     */
    private int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}

代码也不很难,相信各位都能看懂,此段代码使用了线性布局加载imageview和textview,说白了还是用了俩个控件。需要注意的就是我之前说的如果用的是auto这个库,则放开如下代码:

      width = AutoUtils.getPercentWidthSize((int) width);
      height = AutoUtils.getPercentWidthSize((int) height);
      marginTop= AutoUtils.getPercentWidthSize((int)marginTop);

另外需要将继承的类改为普通的布局

public class RichText  extends LinearLayout

2.1 R.layout.view_imagetext 布局代码

  mRoot = inflater.inflate(R.layout.view_imagetext, this, true);

<?xml version="1.0" encoding="utf-8"?>
<com.zhy.autolayout.AutoLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rootView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageView
        android:src="@drawable/ic_launcher"
        android:id="@+id/img"
        android:layout_width="40px"
        android:layout_height="40px"
        android:layout_gravity="center"
        android:layout_marginBottom="3px"
        android:layout_marginTop="8px" />

    <TextView
        android:layout_marginTop="5px"
        android:id="@+id/txt"
        android:text="11111111"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="5px"
        android:gravity="center" />

</com.zhy.autolayout.AutoLinearLayout>

imageview和textview之间的间距通过android:layout_marginBottom和android:layout_marginTop的属性来控制,其他的属性照旧

3.引用代码
上面我们将代码写完了,现在就可以开始引用了(textview原有的属性可以继续使用)

切记一定要先引用auto属性
  xmlns:app="http://schemas.android.com/apk/res-auto"
  
  <com.hangzhou.bijianhuzhu.customView.RichText
            android:id="@+id/rt_index"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            app:img="@drawable/ic_launcher"
            app:img_height="80px"     //设置高度
            app:img_width="80px"      //设置宽度
            app:text="@string/indexpager" //文字
            app:text_size="14" />     //文字大小

全部代码到此为止就结束了。使用这个的好处就是不需要每次写俩个控件了,减少了层级布局,apk性能得到部分优化。其他的属性可以参考attrs文件进行使用。
如果你有更好的解决办法或者是方案,欢迎一起探讨交流!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,475评论 4 372
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,744评论 2 307
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 112,101评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,732评论 0 221
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,141评论 3 297
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,049评论 1 226
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,188评论 2 320
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,965评论 0 213
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,716评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,867评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,341评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,663评论 3 263
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,376评论 3 244
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,200评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,990评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,179评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,979评论 2 279

推荐阅读更多精彩内容