自定义控件InfoTextView展示个人信息

这里写图片描述


像上面展示信息的控件,如果用传统的textview肯定是不够的,一般人都是用布局和控件去叠加,这样效率不高,而且代码量多。


/**
 * 如果用一般控件去堆砌看起来很麻烦
 * 自定义infoTextView,
 * Created by Administrator on 2017-9-1.
 */

public class InfoTextView extends TextView {
    public static final String TAG = "=test=";

    private TextPaint paint;
    private String rightText;
    private int intrinsicWidth;
    private float x;
    private float y;

    public InfoTextView(Context context) {
        this(context, null);
    }

    public InfoTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public InfoTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.InfoTextView);
        rightText = typedArray.getString(R.styleable.InfoTextView_rightText);
        paint = getPaint();
        //获取右边的箭头
        Drawable drawable = ContextCompat.getDrawable(context, R.drawable.lib_more);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        setCompoundDrawables(null, null, drawable, null);
        intrinsicWidth = drawable.getIntrinsicWidth();
        Log.i(TAG, "InfoTextView: " + paint.getTextSize() + "||" + intrinsicWidth + "||" + drawable.getIntrinsicHeight());
        //===========
        typedArray.recycle();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        float top = fontMetrics.top;
        float bottom = fontMetrics.bottom;
        Rect rect = new Rect();
        paint.getTextBounds(rightText, 0, rightText.length(), rect);
        x = w - rect.width() - intrinsicWidth;//中间也可以除去padding,自己随便定义
        float textY = (bottom + top) / 2;
        y = h / 2 - textY;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawText(rightText, x, y, paint);
    }

    //暴露动态设置右边text方法
    public void setRightText(String rightText) {
        this.rightText = rightText;
    }
}
//自定义属性
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="InfoTextView">
        <!--设置右边的text-->
        <attr name="rightText" format="string" />
    </declare-styleable>

</resour

//使用如下图:
这里写图片描述
最终效果运行效果是第一张图,是不是可以节约很多代码,并且提高了效率

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值