8月 012020
本自定义组件实现了一个以高度为标准的正方形TextView组件,如果想以其他标准(最大或者最小宽度、高度)需要再进行修改:
自定义View的代码如下;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import android.content.Context; import android.util.AttributeSet; public class SquareTextView extends android.support.v7.widget.AppCompatTextView { private String LOG_TAG = "SquareTextView"; public SquareTextView(Context context) { super(context); } public SquareTextView(Context context, AttributeSet attrs) { super(context, attrs); } public SquareTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // 先让父类计算宽度和高度 super.onMeasure(widthMeasureSpec, heightMeasureSpec); // 以父类计算的高度获取我们想要的宽度 int w = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY); // 如果只使用setMeasuredDimension会造成对齐效果的失效 // setMeasuredDimension(getMeasuredHeight(), getMeasuredHeight()); // 让父类重新计算 super.onMeasure(w, heightMeasureSpec); } } |
Sorry, the comment form is closed at this time.