Android Edittext: Get LineCount in onCreate () action

How can I do getLineCount () for the Edittext in the onCreate () method for the operation by changing the Edittext text as follows:

@override public void onCreate(Bundle savedInstanceState){ myEditText.setText("EXAMPLE"); myEditText.getLineCount(); } 

Since the view has not yet been drawn, getLineCount () will always return 0. Is there a way around this problem? Thanks!

+2
android oncreate android-edittext settext line-count
source share
3 answers

Ugh, this is a problem with UI everywhere.

You can use a handler. You will publish a Runnable that will receive a row counter and continue processing.

+2
source share

This is definitely a pain. In my case, I did not need to edit, so I worked with TextView , but seeing that EditText comes from TextView , you should use the same approach. I subclassed TextView and implemented onSizeChanged to call a new listener, which I called OnSizeChangedListener . In the listener, you can call getLineCount() with valid results.

TextView :

 /** Size change listening TextView. */ public class SizeChangeNotifyingTextView extends TextView { /** Listener. */ private OnSizeChangeListener m_listener; /** * Creates a new Layout-notifying TextView. * @param context Context. * @param attrs Attributes. */ public SizeChangeNotifyingTextView(Context context, AttributeSet attrs) { super(context, attrs); } /** * Adds a size change listener. * @param listener Listener. */ public void setOnSizeChangedListener(OnSizeChangeListener listener) { m_listener = listener; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if (m_listener != null) { m_listener.onSizeChanged(w, h, oldw, oldh); } } } 
+2
source share

Thanks so much for the last answer, it was very helpful for me!

As a contribution, I would like to add a listener interface code that will be registered in hookCotizeNotifyingTextView (which can be added to the SizeChangeNotifyingTextView class):

 public interface OnSizeChangeListener { public void onSizeChanged(int w, int h, int oldw, int oldh); } 

Finally, to register a listener, you can do this as follows:

 tv.setOnSizeChangedListener(new SizeChangeNotifyingTextView.OnSizeChangeListener() { @Override public void onSizeChanged(int w, int h, int oldw, int oldh) { ... } }); 
+1
source share

All Articles