您好我正在尝试使用TextView,它有以下约束:
所以现在我有一个EditText,允许用户输入文本,每个角色用户输入,TextView将反映用户输入的内容,并根据上述规则更改字体大小。
userEditView.addTextChangedListener(
new TextWatcher() {
@Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
float fontSize = 30;
userTextView.setTextSize(fontSize);
int userTextViewWidth = userTextView.getWidth();
int userTextViewContainerWidth = parentRelatievLayOutView.getWidth();//parentRelativeLayout is a RelativeLayout in xml
// logic here => i want to know when to wrap a line, i should wrap when the textView width is same or greater than the parent container, in such case, we reduce the font size, and then get the new textView width, see if it can be fit in one line or not
while (userTextViewWidth >= userTextViewContainerWidth) {
fontSize -= 1;
if (fontSize <= 12) {
fontSize = 12;
break;
}
userTextView.setTextSize(fontSize);
//userTextView.append("\uFEFF"); // does not work
//userTextView.invalidate(); // does not work
userTextViewWidth = userTextView.getWidth();// *** this line never gets updated
}
}
@Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
userTextView.setText(charSequence);
}
@Override public void afterTextChanged(Editable editable) {
}
});
所以我的问题是userTextViewWidth = userTextView.getWidth()
永远不会更新,即字体大小变小,宽度仍然相同...我想改变它
android有一个问题,TextView的大小没有改变Android:TextView height doesn't change after shrinking the font size,但我试过,它提供的技术都没有用。
答案 0 :(得分:3)
您需要做的是测量textView。
而不是
userTextViewWidth = userTextView.getWidth();
使用
// find out how wide it 'wants' to be
userTextView.measure(MeasureSpec.UNSPECIFIED, userTextView.getHeight());
userTextViewWidth = userTextView.getMeasuredWidth();
更多信息位于http://developer.android.com/reference/android/view/View.html#Layout
答案 1 :(得分:0)
设置android:layoutWidth="wrap_content"
,textview将根据文本长度缩放宽度大小。 AFAIK,无法根据文本大小自动调整textview的大小。