I have a TextView in my layout which has a width set to match_parent and height set as wrap_content. The layout has a padding of say 10dp, textSize as 15sp and noofLines as 2. I would like to calculate the maximum no of letters that can fit this specific textView.
Asked
Active
Viewed 239 times
0
-
2You could approximate since not all characters have the same width. – TheKarlo95 Dec 19 '18 at 13:44
-
Probably makes more sense to use - android:maxLength="65" instead of calculating the max number of characters to be used? – Nero Dec 19 '18 at 13:50
-
Possible duplicate of [How to find android TextView number of characters per line?](https://stackoverflow.com/questions/5970640/how-to-find-android-textview-number-of-characters-per-line) – Mauker Dec 19 '18 at 13:54
-
You could rewrite TextView, in the custom TextView to implement a calculation method, get the number of lines with the maximum number of words per line, I wrote a simple custom TextView, do you need me to add to the answer. – Leo Zhu Dec 20 '18 at 02:31
-
@LeoZhu Sure. Would be a reference to start with. – Midhun Kumar Dec 20 '18 at 05:35
-
could it work ? – Leo Zhu Dec 27 '18 at 03:34
1 Answers
0
This is a simple Custom TextView:
public class MyTextView : AppCompatTextView
{
public MyTextView(Context context) : base(context)
{
}
public MyTextView(Context context, IAttributeSet attrs) : base(context, attrs)
{
}
public MyTextView(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr)
{
}
public int GetEstimatedLength()
{
int height = Height;
int lineHeight =LineHeight;
int linecount = height / lineHeight;
float textSize = TextSize;
float linewords = Width / textSize;
return (int)(linecount * (int)linewords);
}
}
then in your axml:
<MyTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lines="2"
android:textSize="31sp"
android:id="@+id/myTextView1" />
finally in the activity :
MyTextView myTextView = FindViewById<MyTextView>(Resource.Id.myTextView1);
int numbers = myTextView.GetEstimatedLength();
"numbers" is the maximum number of characters,it has no effect on the sign

Leo Zhu
- 15,726
- 1
- 7
- 23