1
votes

Newbie Java question - On all the posts for Auto Scaling the Text view, no one indicates how you actually use the provided class. It looks like one of the better solutions is Chase's at Auto Scale TextView Text to Fit within Bounds

Does anyone have an idea how you use it? For example:

String bigTextString = "This is a test!";

TextView t = (TextView)findViewById(R.id.big_text);
t.setTextSize(returnFontSize(bigTextString));
t.setText(bigTextString);

The returnFontSize does not exist and is just shown for illustration. The AutoResizeTextView class is set up properly in it's own file.


Thanks (ignore the short comment below, as StackOverflow has a bug that doesn't allow reediting a comment, and it's also limited to 512 chars).

I must be still missing something. If I only use the two lines suggested where do you pass the text string? I tried something similar, but it just crashes when run, which makes sense.

AutoResizeTextView t = new AutoResizeTextView(this); 
linearMain.addView(findViewById(R.id.big_text));

The addView fails with a "IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.", which seems strange as I don't want to remove the view (I think), and I don't see how it has any idea of the string to put on screen.

Is a addView really necessary as it's already defined in the layout.

I just want to pass it the text. For example:

TextView t = (TextView)findViewById(R.id.big_text);
t.setTextSize(textSize);
t.setTextColor(textColor);
t.setText(bigTextString);

This runs, except Android does a poor job of fitting the text on screen depending on what's in "bigTextString".

1

1 Answers

0
votes

Well if you have a class that describes how to make and modify an object, all you need to do is make it and modify it with its constructor and methods. Below is the one from your link.

public FontFitTextView(Context context, AttributeSet attrs) {
    super(context, attrs);

    float size = this.getTextSize();
    if (size > MAX_TEXT_SIZE)
        setTextSize(MAX_TEXT_SIZE);
}

You call in your activity FontFitTextView textViewName = new FontFitTextView(context, attrs); and then add it to a view by layoutName.addView(textViewName); This means you need to find the view you are using for a layout by its android:id as I am assuming you dont want to build the whole layout programatically. You can also call the constructor in xml by <packagename.FontFitTextView />

tl;dr - Use the constructor