您的位置:首页 > 移动开发 > Android开发

android:hint属性对TextView(或者EditText)的影响--源码分析

2017-07-26 17:35 1041 查看
textView.setText("哈哈");

textView.setHint("哈哈哈哈哈哈");

hint属性对TextView(或者EditText)的影响,直接看下图:

使用上下两个TextView控件进行对比,

第一行的“哈哈哈哈哈哈哈”是作为对比的TextView,第二行的“哈哈”是上面代码操作的TextView



找到TextView的onMeasure方法

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

..........省略...............

if (mHint != null) {
int hintDes = -1;
int hintWidth;

if (mHintLayout != null && mEllipsize == null) {
hintDes = desired(mHintLayout);
}

if (hintDes < 0) {
hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mTextDir, mHintBoring);
if (hintBoring != null) {
mHintBoring = hintBoring;
}
}

if (hintBoring == null || hintBoring == UNKNOWN_BORING) {
if (hintDes < 0) {
hintDes = (int) Math.ceil(Layout.getDesiredWidth(mHint, mTextPaint));
}
hintWidth = hintDes;
} else {
hintWidth = hintBoring.width;
}

if (hintWidth > width) {
width = hintWidth;
}
}

}


if (mHint != null){

if (hintWidth > width) {

             width = hintWidth;

        }

}

所以 如果设置了hint属性, 在onMeasure测量TextView宽高时候,一定会把hint计算进去,当实际text字符比hint字符少,就会出现如文章开始处的效果。

解决方案:用text模拟hint

textView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {

}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println("onTextChanged--"+s);
if (TextUtils.isEmpty(s)){
textView.setText("模拟hint文字");
//这里设置为hint字体,一定要在setsetText("模拟hint文字") 之后
//因为setText("模拟hint文字")的时候,还会调用onTextChanged
//这是个小瑕疵
textView.setTextColor(Color.BLUE);
}else {
textView.setTextColor(Color.RED);
}
}

@Override
public void afterTextChanged(Editable s) {
//在这里也能实现
}
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: