像上面展示信息的控件,如果用传统的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
//使用如下图:
最终效果运行效果是第一张图,是不是可以节约很多代码,并且提高了效率