2015年7月24日 星期五

android 由程式觸發點擊事件(OnClickListener)

目的:

如何藉由程式直接觸發元件的點擊事件?

Button

Button.performClick() ;

TextView



TextView.performClick() ;


直接這樣做會發現到會發生NullPointer Exception


原因是有可能點擊事件雖然有設定了,但TextView為準備完成,所以造成NullPointer Exceptino,因此使用以下方式進行解決,

TextView.post( new Runnable() {
    public void run() {
        TextView.performClick() ;
    }
} ) ;

利用Runnable直接在interface thread中執行

reference:
http://stackoverflow.com/a/11035166

沒有留言:

張貼留言