get width of textview in characters - android

I think this is the opposite of
Set width of TextView in terms of characters
I have a TextView where I'm showing some report data. I use a monospace TypefaceSpan for a portion of it because I want columns to line up.
I used my test Android device to figure out how many columns I could fit, but the Android emulator seems to have exactly one less column, which makes things wrap in an ugly way in portrait mode.
Is there a way to find out how many characters should fit on 1 line?

The answer would be to use the breakText() of your textView's Paint Object. Here is a Sample ,
int totalCharstoFit= textView.getPaint().breakText(fullString, 0, fullString.length(),
true, textView.getWidth(), null);
Now totalCharstoFit contains the exact characters that can be fit into one line. And now you can make a sub string of your full string and append it to the TextView like this,
String subString=fullString.substring(0,totalCharstoFit);
textView.append(substring);
And to calculate the remaining string, you can do this,
fullString=fullString.substring(subString.length(),fullString.length());
Now the full code,
Do this in a while loop,
while(fullstirng.length>0)
{
int totalCharstoFit= textView.getPaint().breakText(fullString, 0, fullString.length(),
true, textView.getWidth(), null);
String subString=fullString.substring(0,totalCharstoFit);
textView.append(substring);
fullString=fullString.substring(subString.length(),fullString.length());
}

Well you could do math to find this out, find the width of the character, divide the width of the screen by this, and you'd have what you're looking for.
But is it not possible to design it better? Are there any columns you can group together? Display as a graphic, or even exclude completely?
Another possible solution is to use something like a viewpager. (Find out how many columns' width fit on the first page, and then split the remaining tables onto the second page).

You can get total line of Textview and get string for each characters by below code.Then you can set style to each line whichever you want.
I set first line bold.
private void setLayoutListner( final TextView textView ) {
textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
textView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
final Layout layout = textView.getLayout();
// Loop over all the lines and do whatever you need with
// the width of the line
for (int i = 0; i < layout.getLineCount(); i++) {
int end = layout.getLineEnd(0);
SpannableString content = new SpannableString( textView.getText().toString() );
content.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, end, 0);
content.setSpan(new StyleSpan(android.graphics.Typeface.NORMAL), end, content.length(), 0);
textView.setText( content );
}
}
});
}
Try this way.You can apply multiple style this way.
You can also get width of textview by:
for (int i = 0; i < layout.getLineCount(); i++) {
maxLineWidth = Math.max(maxLineWidth, layout.getLineWidth(i));
}

Related

Format first line of a multiline TextView in Android

I have multiline TextView, I need to format only single line of it. Since font size and style is dynamic I need it to format "first line" automatically.
This TextView is displaying a string without linefeed, it is wrapped automatically, I need to format first wrapped line.
Please check attached image:
I found the solution that uses StaticLayout.
private TextView tvTitle; //bold title with maxLines = 1
private TextView tvText; //the rest of the text
//initialize views, etc...
private void showText(#Nonnull String text) {
tvTitle.setText(text);
tvTitle.post(() -> {
String ellipsizedText = getEllipsizedText(text, tvTitle);
tvText.setText(ellipsizedText);
});
}
private static String getEllipsizedText(String text, TextView textView) {
StaticLayout staticLayout = getStaticLayout(text,
textView.getPaint(),
textView.getWidth(),
1,
null);
return text.substring(staticLayout.getLineEnd(0));
}
private static StaticLayout getStaticLayout(CharSequence text,
TextPaint paint,
int width,
int maxLines,
TextUtils.TruncateAt ellipsize) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return StaticLayout.Builder.obtain(text, 0, text.length(), paint, width)
.setTextDirection(TextDirectionHeuristics.FIRSTSTRONG_LTR)
.setAlignment(Layout.Alignment.ALIGN_NORMAL)
.setLineSpacing(0f, 1f)
.setIncludePad(false)
.setEllipsize(ellipsize)
.setEllipsizedWidth(width)
.setMaxLines(maxLines)
.build();
} else {
return new StaticLayout(text,
paint,
width,
Layout.Alignment.ALIGN_NORMAL,
1f,
0f,
false);
}
}
from #HiteshGehlot's answer:
myTextView.setText(Html.fromHtml("<b>This is a normal</b><br>second line<br>third line"));
but as your system is dynamic, this is not a good way to do it. This code generates the appropriate HTML:
String lines[] = string.split("\\n");
String fl = String.format(Locale.ENGLISH, "<b>%s</b><br>", lines[0]);
StringBuilder sb = new StringBuilder();
sb.append(fl);
for(int i = 1; i < lines.length; i++){
sb.append(lines[i] + "<br>");
}
String finalProduct = sb.toString();
then:
myTextView.setText(Html.fromHtml(finalProduct));
This should dynamically create the HTML tags for the first line
EXPLANATION
This is an improvement from a previous answer. Using HTML, the first line is formatted as bold.
Using regex, we split all the lines by newline(\n). The first String in the array is the first line, while the rest aren't important to format. So first we append the first line, and add the rest after that. The for-loop starts at 1 since 0 is the first line.
NOTE
If you do break the text dynamically, you pass that String into the method above. The method I have presented here uses those linebreaks to figure out which line is where, to be able to set the first line to be bold
try this:
myTextView.setText(Html.fromHtml("<b>This is a normal</b><br>second line<br>third line"));
Just use another TextView.
TextView1, TextView2, TextView3.
And set TextView1 to bold.

Set ascent, descent, baseline of text in TextView

I need two TextViews to have same baseline, ascent, bottom, descent values. Is it possible to change the FontMetrics of TextView after text has been drawn?
It is so late, but I also confronted with this issue, and I solve with some tricks. (just modify baseline, not ascent, descent or something)
note that fontMetrics' values(ascent, descent, bottom, top) are depend on textSize.
so we must use fontMetrics' values after view is drawn. (if it is autoSizing or something)
to do something after view drawn, using Sa Qada's answer
baseline is always 0. descent, ascent, top, bottom is relative values.
refer this Suragch's answer.
change fontMetrics' values does not affect to UI.
to set custom baseline(text position of textview), just use padding.
below code is align to baseline with two TextView.
// this is kotlin code, but I'm sure you can understand
// align textview2 to textview1's baseline
val tv1Baseline = tv1.paddingBottom + tv1.paint.fontMetrics.bottom
val tv2Baseline = tv2.paddingBottom + tv2.paint.fontMetrics.bottom
val newPaddingOffset = tv1Baseline - tv2Baseline
tv2.setPadding(tv2.paddingLeft, tv2.paddingTop, tv2.paddingRight,
tv2.paddingBottom + newPaddingOffset)
Here's solution to align baselines (note the difference from bottom in Suragch answer and definition of return value of TextView.getBaseline()) which alignes tv2 baseline to tv1s':
private void alignWeatherTextBaseline(View tv1, View tv2) {
int tv1Baseline = tv1.getTop() + tv1.getBaseline();
int tv2Baseline = tv2.getTop() + tv2.getBaseline();
int newPaddingOffset = tv1Baseline - tv2Baseline;
if (newPaddingOffset != 0) {
tv2.setPadding(tv2.getPaddingLeft(),
tv2.getPaddingTop(), tv2.getPaddingRight(),
tv2.getPaddingBottom() - newPaddingOffset);
}
}
Be aware of the following:
if multiline text is possible, you need to write proper getLastLineBaseline() and use it instead of standard getBaseline()
you can get invalid value (0 or -1) from getBaseline() if a view hasn't been layout yet

Creating a dynamic textview where orientation depends on screen and text size

I have an array of strings(dynamic). I have to show that strings in a textview. The size of the string may vary. The first string is "check", the second String is "my head is breaking" and so on. I want the textview to adjust itself. Say for ex : If the first textview occupied less than half of the screen, The second textview will be next to it. Else, The 2nd Textview will be placed at the next row.
Please check the following image.
How can i achieve like this?
I'm not native speaker.
In order to achieve your purpose you need to follow these steps:
1. Find the dimensions of your device: I did this some time ago, here you have my implementation.
protected void loadDeviceDimensions(){
Point size = new Point();//Calcular Width y Height.
WindowManager w = getWindowManager();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2)
{
w.getDefaultDisplay().getSize(size);
DeviceWidth = size.x;
DeviceHeight = size.y;
}
else
{
Display d = w.getDefaultDisplay();
DeviceWidth = d.getWidth();
DeviceHeight = d.getHeight();
}
}
Once you have the device dimensions the next step is create the text fields, the text, font, and all the other stuffs. Don't worry about the position, just create the fields
Once you have your fields created with their text and font set, its time to set their position. For these purpose you will need to use the TextView.getWidth() and TextView.getHeight(). The code should look like this.
for(int i=0, i < textView-1 , i++) {
if( textViews[i].getWidth <= deviceWidth/2 && textViews[i+1].getWidth <= deviceWidth/2){
//Put the two text fields on the same line
i++;//Don't forget this line.
}else{
//Put only one text field on the line.
}
}
You can check your Display size, and you can check your size the TextView will have. then it should not be a problem, otherwise let me know.
display size
textview size without to draw first

Google Currents like page-by-page reading style

I'm learning how to implement one-page reading style, like in Google Currents, for my app.
The contents(text) are adjusted based on the screen size and there is no scroll, no zoom.
The overflowed text are in the next page. (I knew that it is using ViewPager.)
Here is the screen shoots:
My questions are:
how can I fit(adjust) the contents(text) to the screen?
how can I automatically parse overflowed text to the next screen? (so that the user
will only need to swipe between screens for reading.)
Also, I'm considering to use TextView for the content. (GoogleCurrent used WebView, I think) My app don't need to use WebView. Will it be possible for textview to achieve like that?
I implemented something like this with several TextViews. First of all, I created a ViewPager for swyping between TextViews.
After than I separate long text to several blocks, one per page.
To get text for page I use this function:
TextView tv = new TextView(context); //creating text view
int width = mtv.getWidth() - tv.getPaddingLeft()-tv.getPaddingRight(); //get width for text
int lHeight = tv.getLineHeight(); getting line height
int height = ((View)mtv.getParent()).getHeight() - tv.getPaddingBottom()-tv.getPaddingTop(); // getting height of text
int linesCount = (int)Math.floor((float)height/lHeight); // get line count on page
String tmpText = "";
for (int i =0; i<linesCount; i++)
{
int index = Math.min(mtv.getLayout().getPaint().breakText(text, true, width, new float[0]), text.indexOf('\n')+1); // breaking text to lines. To use this you need mtv to be measured
String t = text.substring(0, index); //getting text for this textview
if (index+1 < text.length() && (text.charAt(index+1)!=' ' || text.charAt(index+1)!='\n') && t.lastIndexOf(" ")>0)
index = t.lastIndexOf(" ")+1; // hack for situation when line starts with " "
text = text.substring(index);//getting text for next iteration
t = t.substring(0, index);
tmpText+=t;
}
//I use spannable string for links and some styles. Recalculating spans for new indexes
SpannableString s = new SpannableString(tmpText);
Object os[] = spanned.getSpans(offset, offset + tmpText.length(), Object.class);
for (Object o: os)
{
int start = spanned.getSpanStart(o)-offset;
int end = spanned.getSpanEnd(o)-offset;
if (start < 0)
start = 0;
if (end>=s.length())
end = s.length()-1;
s.setSpan(o, start, end, spanned.getSpanFlags(o));
}
offset+=tmpText.length();
while (text.startsWith(" ") || text.startsWith("\n"))
{
text = text.substring(1);
offset++;
}
tv.setText(s);
Nad I think, that google uses TextView, not webView. Read about Spanned and Spannable. It's have ability to show links, images, text with different styles in one textView.

last word displayed in a textview

I'm going to display a complete text document on several pages in an android app. Each page contains a TextView control which is in charge to display text. It also contains a next button, which is in charge to update textview and follow the text just from where it ended in last displayed section.
The problem is how can i find the last displayed word in displayable area of TextView?
Note: In this app, textView is not supposed to be scrolled or use ellipsize.
It also must be noted textsize can be increased or decreased.
To understand the situation better:
Sample Text to be displayed:
This is whole text. At first Page It just ended here and must be
followed from here.
And this is the sample illustration of the its display. The question is how to find word "here" as last word displayed in page 1?
I can't try this idea now but let's give it a shot! According to this post you can use the following method to find out if a string fits in a textview.
private boolean isTooLarge (TextView text, String newText) {
float textWidth = text.getPaint().measureText(newText);
return (textWidth >= text.getMeasuredWidth ());
}
So one idea, if the text is always the same, you can define the initial values for each text view manually and then when you increase or decrease the font you recalculate it, removing or adding words.
If it's not an option to input the initial values manually you can do something like:
String wordsInTextview = new String();
int lastUsedWord= 0;
int totalNumberOfWords = text.size();
for (int i=lastUsedWord;i<totalNumberOfWords;i++) {
if !(isTooLarge(TextView,wordsInTextview)) {
wordsInTextview = wordsInTextview + text(i); // add the words to be shown
} else {
TextView.setText(wordsInTextView);
lastUsedWord= i;
wordsInTextView = new String(); // no idea if this will erase the textView but shouldn't be hard to fix
}
}
You also would need to store the position of the first word of the textView, so when you resize the text you know where to start from!
int firstWordOnTextView = TextView.getText().toString().split(" ")[0]
And when it resizes you use it in the same method to calculate the text on the screen.
lastUsedWord = firstWordOnTextView;
If you want to be even faster, you can keep a track of how many words you have on each page, make an average and after a few runs always stat your loop from there. Or a few words before to avoid having to iterate back.
I believe this a reasonable solution if you don't have to display too many pages at once!
Sorry for mistakes in the code I don't have where to try it now! Any comments about this solution? Very interesting question!
Finally I developed piece of code which can find last displayed word.
Considering that we are going to use a text view with properties width and height as its size and textSize in dp as size of text, function formatStringToFitInTextView evaluates the last displayed word in the textview and returns it to as function output.
In below sample we considered SERIF font as TextView typeface.
String formatStringToFitInTextView(int width, int heigth, String inputText,float textSize) {
String[] words;
String lastWord = "";
String finalString="";
StaticLayout stLayout;
int i,numberOfWords;
int h;
Typeface tf = Typeface.SERIF;
TextPaint tp = new TextPaint();
tp.setTypeface(tf );
tp.setTextSize(textSize); //COMPLEX_UNIT_DP
words = inputText.split(" "); //split input text to words
numberOfWords = words.length;
for (i=0;i<numberOfWords;i++){
stLayout= measure(tp,finalString+words[i]+" ",width);
h=stLayout.getHeight();
if (stLayout.getHeight() > heigth) break;
finalString += words[i]+" ";
lastWord = words[i];
}
return lastWord;
}
StaticLayout measure( TextPaint textPaint, String text, Integer wrapWidth ) {
int boundedWidth = Integer.MAX_VALUE;
if( wrapWidth != null && wrapWidth > 0 ) {
boundedWidth = wrapWidth;
}
StaticLayout layout = new StaticLayout( text, textPaint, boundedWidth, Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false );
return layout;
}
The total logic to do actions is split the input text into words and add words one by one to textview till it fills up the provided height and width and then return the last added word as last displayed word.
Note: Thanks to Moritz, I used function measure from this answer.

Categories

Resources