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

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



  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值