Android Edittext: Get LineCount in an Activity's onCreate()

痴心易碎 提交于 2019-12-24 01:25:17

问题


How can I do getLineCount() of an Edittext in the onCreate() method of an activity, having changed the Edittext's text, like the following:

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

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


回答1:


Ugh, it's a problem with UI everywhere.

You can use a Handler. You'll post a Runnable that will get the line count and continue the processing.




回答2:


This is definitely a pain. In my case I didn't need editing, so I worked with TextView but seeing as EditText derives from TextView you should be able to 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.

The 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);
        }
    }
}



回答3:


Thanks a lot for the last answer, it was very helpful to me!

As a contribution, I would like to add the code of the listener interface that will be registered to the SizeChangeNotifyingTextView's hook (which can be added inside 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 it this way:

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


来源:https://stackoverflow.com/questions/8086321/android-edittext-get-linecount-in-an-activitys-oncreate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!