问题:项目中需要根据字符串的长度判断Textview的高度
一、如果全是英文的也比较容易,根据长度判断从而设置mTextView的高度就好。
double temp = str.length(); if (temp > 36) { mTextView.height = 350; } else { mTextView.height = 220; }
之后更新界面布局就好。
根据我的字体大小来说,这只是一个关于Textview的2行和4行的设定。
二、字符串如果中英文都有的话,由于中文和英文一个字符所占的宽度不同,则需要一个转化的方法。
if (!str.equals("")) { char[] chars = str.toCharArray(); double temp = str.length(); for (int i = 0; i < chars.length; i++) { byte[] bytes = ("" + chars[i]).getBytes(); if (bytes.length == 3) { //英文的bytes.length为1,中文的bytes.length为3 temp += 0.8; //根据我的字体大小,不断的调整好,大概是中文和英文一个字符1.8倍的关系,不同字体可能不同 } } if (temp > 36) { mTextView.height = 350; } else { mTextView.height = 220; }
三、TextView中的字符串改变了,同时也可以用TextWatcher来改变其高度。
类的说明:
TextWatcher fieldValidatorTextWatcher = new TextWatcher() { @Override public void afterTextChanged(Editable s) { //表示最终内容 Log.d("afterTextChanged", s.toString()); } @Override public void beforeTextChanged(CharSequence s, int start/*开始的位置*/, int count/*被改变的旧内容数*/, int after/*改变后的内容数量*/) { //这里的s表示改变之前的内容,通常start和count组合,可以在s中读取本次改变字段中被改变的内容。而after表示改变后新的内容的数量。 } @Override public void onTextChanged(CharSequence s, int start/*开始位置*/, int before/*改变前的内容数量*/, int count/*新增数*/) { //这里的s表示改变之后的内容,通常start和count组合,可以在s中读取本次改变字段中新的内容。而before表示被改变的内容的数量。 } };
在其中实现相关textview的设置就好。我的代码如下:
TextWatcher mAutoScrollWatcher = new TextWatcher() { @Override public void afterTextChanged(Editable s) { ...... } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { int lineCount = mTextView.getLineCount(); int linesCount= 2; //改变前的行数 if (lineCount <= 2) { if (linesCount == 4) { linesCount = 2; mTextView.height = 220; } } else if (lineCount > 2) { if (linesCount == 2) { linesCount = 4; mTextView.height = 350; } }
...... } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { ...... } } };
直接根据mTextView.getLineCount()方法来获得行数,比较准确。
只是初始化textView时会有问题,我是直接把行数设置为2的。
--------------------------------------------------------------------------------------------
刚开始学习,写博客只是希望能记录自己的成长轨迹,欢迎大家指点。