TextView内マージンなし
2945 ワード
NoPaddingTextView
attrs
package widget.textview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;
import com.xalikai.bnmdteacherend.R;
/**
* Created on 2019/3/14.
*
* @author
* @desc NoPaddingTextView
*/
public class NoPaddingTextView extends AppCompatTextView {
private Paint paint = getPaint();
private Rect rect = new Rect();
/**
* (true 、false )
*/
private Boolean toRemoveTheInBodyMargin = false;
public NoPaddingTextView(Context context) {
super(context);
}
public NoPaddingTextView(Context context, AttributeSet attrs) {
super(context, attrs);
initAttributes(context, attrs);
}
public NoPaddingTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initAttributes(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (toRemoveTheInBodyMargin) {
calculateTextParams();
setMeasuredDimension(rect.right - rect.left, -rect.top + rect.bottom);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected void onDraw(Canvas canvas) {
drawText(canvas);
}
/**
*
*
* @param context
* @param attrs
*/
private void initAttributes(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.NoPaddingTextView);
toRemoveTheInBodyMargin = typedArray.getBoolean(R.styleable.NoPaddingTextView_removeDefaultPadding, false);
typedArray.recycle();
}
/**
*
*/
private String calculateTextParams() {
String text = getText().toString();
int textLength = text.length();
paint.getTextBounds(text, 0, textLength, rect);
if (textLength == 0) {
rect.right = rect.left;
}
return text;
}
/**
*
*/
private void drawText(Canvas canvas) {
String text = calculateTextParams();
int left = rect.left;
int bottom = rect.bottom;
rect.offset(-rect.left, -rect.top);
paint.setAntiAlias(true);
paint.setColor(getCurrentTextColor());
canvas.drawText(text, (float) (-left), (float) (rect.bottom - bottom), paint);
}
}
attrs