1.这次给大家带来了一个自定义控件:edittext,话不多说,老规矩先上图
2.控件继承自frameLayout,内部包含了3个子控件:editText,textView,imageView,其中editText是用于输入文字,textView的作用是显示“测试”的标签并执行移动缩小动画,imageView的作用是在输入文字后显示删除按钮。接下来是重点代码分析部分:
测量子控件的大小onMeasure():控件高度等于editText+textView的高度,为移动动画提供空间。
private int measureHeight(int heightMeasureSpec) {int specMode = MeasureSpec.getMode(heightMeasureSpec);int specSize = MeasureSpec.getSize(heightMeasureSpec);int result = 0;if (specMode == MeasureSpec.EXACTLY) {result = specSize;} else {result = mEditText.getMeasuredHeight() + mLabel.getMeasuredHeight();result += getPaddingTop() + getPaddingBottom();result = Math.max(result, getSuggestedMinimumHeight());if (specMode == MeasureSpec.AT_MOST) {result = Math.min(result, specSize);}}return result;}
确认控件位置:onLayout()
editText的位置等于自身的高度+textView的高度
@Overrideprotected void onLayout(boolean changed, int left, int top, int right, int bottom) {final int childLeft = getPaddingLeft();final int childRight = right - left - getPaddingRight();int childTop = getPaddingTop();final int childBottom = bottom - top - getPaddingBottom();layoutChild(mLabel, childLeft, childTop, childRight, childBottom);layoutChild(mEditText, childLeft, childTop + mLabel.getMeasuredHeight(), childRight, childBottom);layoutChild(mDel, childLeft, childTop, childRight, childBottom);}private void layoutChild(View child, int parentLeft, int parentTop, int parentRight, int parentBottom) {if (child.getVisibility() != GONE) {final FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) child.getLayoutParams();final int width = child.getMeasuredWidth();final int height = child.getMeasuredHeight();int childLeft;final int childTop = parentTop + lp.topMargin;if (child.getId() == mDel.getId()) {childLeft = parentLeft + lp.leftMargin + mEditText.getMeasuredWidth() - width - 10;} else {childLeft = parentLeft + lp.leftMargin;}Log.d("layoutChild", child.getId() + "位置:" + childLeft + ";" + childTop + ";" + (childLeft + width) + ";" + (childTop + height));child.layout(childLeft, childTop, childLeft + width, childTop + height);}}
最后一步绘制,并没有调用onDraw()放法,而是在控件init时,直接将xml布局文件添加到frameLayout parent上了。
View rootView = inflate(context, R.layout.libui_edittextlabel, this);mEditText = (EditText) findViewById(R.id.libui_edittext_edittext);mLabel = (TextView) findViewById(R.id.libui_edittext_label);mDel = (ImageView) findViewById(R.id.libui_edittext_del);
到此控件绘制完毕。至于动画效果,参见源码:/sougoucm/editTextView
如果觉得《自定义控件-----输入框》对你有帮助,请点赞、收藏,并留下你的观点哦!