Reputation: 1275
Hi I am trying to have a TextView, it has the following constraints:
So now I have a EditText, which allows user to type text, and each character user enters, the TextView will reflect what users types, and change in font size accordingly to the rule above.
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) {
}
});
So my problem is userTextViewWidth = userTextView.getWidth()
never gets updated, i.e. with font size becomes smaller, width is still the same... I want to change that
there is an issue with android where TextView size is not changed Android:TextView height doesn't change after shrinking the font size but I tried, none of the techniques it provides worked.
Upvotes: 2
Views: 2771
Reputation: 14142
What you need to do is measure your textView.
instead of
userTextViewWidth = userTextView.getWidth();
use
// find out how wide it 'wants' to be
userTextView.measure(MeasureSpec.UNSPECIFIED, userTextView.getHeight());
userTextViewWidth = userTextView.getMeasuredWidth();
More info is at http://developer.android.com/reference/android/view/View.html#Layout
Upvotes: 3
Reputation: 24423
Set android:layoutWidth="wrap_content"
, the textview will scale the width size base on text length in it. AFAIK, no way to auto resize textview base on textsize.
Upvotes: 0