My program reads data from a file and displays it in a TextView . I need to determine the number of virtual pages into which the text of the file is divided. The height / width of one page = height / width of the entire screen. Algorithm, how to calculate, I developed. Here is the code:

 countOfLines = (text.getHeight() / text.getLineHeight()); pages = Math.round(text.getLineCount() / countOfLines) + 1; pagesView.setText(currentPage + "/" + pages); 

text - TextView with text. countOfLines - number of pages. pagesView - TextView which displays the number of pages.

So, the problem is, I need to determine the number of pages immediately after the content is displayed, but when I try to execute this code in any of the lifecycle methods, text.getHeight() always returns 0. But outside the lifecycle methods, the application returns the correct value . So how should I be?

    2 answers 2

    During the call to the onCreate(...) , onStart() and onResume() widgets are not drawn on the screen yet, so, in particular, the getHeight() method returns zero.

    It is worth paying attention to the fact that if you open the activation, then collapse the application and return to it again (provided that the activation was not destroyed), in the onStart() and onResume() getHeight() widget's onResume() method returns the correct value.

    The correct size of the widget can be obtained after it is drawn. You can catch the end of the draw event (in particular, it) by setting OnGlobalLayoutListener object of the corresponding widget and implementing the onGlobalLayout() method:

     mTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { int textViewHeight = mTextView.getHeight(); } }); 

    After getting the result, do not forget to delete the installed OnGlobalLayoutListener (since the onGlobalLayout() method will be called at each redrawing view ).

      Probably you are trying to get the height in onCreate() ? The fact is that until this method is executed, View will not get dimension. You can get the height only after the onCreate() method, for example, by soft-clicking on TextView

      Drum roll ... (not sure, because I did not try)

      LIFEHACK

      In the xml in the tag TextView add

       android:clickable = "true" 

      When you need to get the height of TextView (think over the logic so that this method is called not in onCreate () ), press it programmatically

        textView.performClick(); 

      onCreate() listener

       textView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { TextView tv = ((TextView)v); float height = tv.getHeight(); } } 

      PS Still, try calling performClick in onCreate() . I think that the View that comes in the method should know its height

      PSS Again, the method is not proven