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) {
//在这里也能实现
}
});