1

I get null in Layout object which I try to obtain from a Textview each time after configuration change. The method containing the code is called from onResume().

I suspect I need to do some additional setup for it.

I have studied similar questions, but there isn't a clear answer to it.

What is the event which signals that Layout is ready after configuration changes? Is there some documentation for it?

EDITED:

public class BookDisplayAct extends Activity implements View.OnClickListener {
...
private TextView textView;
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView = (TextView) findViewById(R.id.textViewMain);
        textView.setPadding(15, 15, 15, 15);
...
}

@Override
    protected void onResume() {
...
    renderBookView();
}

    public void renderBookView() {
...
    justifyText(spannable, textView);
...

}

    private Spannable justifyText(Spannable spannable, TextView textView) {
    Layout layout = textView.getLayout();
    int line_count = layout.getLineCount();
...
}

I get the NullPointer exception with the last line.

Bord81
  • 525
  • 2
  • 8
  • 23
  • Possible duplicate of [How to use textview.getLayout()? It returns null](https://stackoverflow.com/questions/16558948/how-to-use-textview-getlayout-it-returns-null) – Giacomo Lai Jul 11 '17 at 17:19
  • Maybe, but there is no exact answer, IMO. I've added the code. Thanks. – Bord81 Jul 11 '17 at 17:34
  • It says there 'This only works after the layout phase, otherwise the returned layout will be null, so call this at an appropriate place in your code.' So what's this 'appropriate place'? – Bord81 Jul 11 '17 at 17:43

1 Answers1

1

Just change your justifyText method as below

 private Spannable justifyText(Spannable spannable, TextView textView) {
    ViewTreeObserver observer= textView.getViewTreeObserver();
    observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            Layout layout = textView.getLayout();
            int line_count = layout.getLineCount();
        }
    });
    ...
}
Giacomo Lai
  • 494
  • 3
  • 15