2017-06-20 45 views
1

我想在EditText中顯示一些文本,並在文本顯示後立即做一些工作。我有下面的代碼在我onCreate()方法:Android:如何在渲染setText()後立即執行回調

this.editor.setText(text, TextView.BufferType.EDITABLE); 
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { 
    @Override 
    public void run() { 
     // Work that needs to be done right after the text is displayed 
    } 
}, 1000); 

該工程確定,但我想setText()渲染和工作是done--一個1秒的延遲是不可接受的延遲減到最小。但是,如果我將延遲更改爲0ms或1ms,則工作在文本呈現之前完成。

我可以保持打字號碼尋找完美的延遲時間,將執行我的代碼文本被渲染剛過,但似乎非常繁瑣/不精確。有沒有更好的方式告訴Android在發生這種情況後立即執行回調?謝謝。

編輯:以下是我嘗試過的兩件事情沒有奏效。對於獎勵積分,如果你能向我解釋爲什麼這些不起作用,這將是非常有幫助的。

使用Handler.post

new Handler(Looper.getMainLooper()).post(r)也運行r文本渲染完成之前。我以爲setText將渲染代碼添加到隊列中,所以不應該在post(r)之後調用那個渲染代碼後添加r

使用View.post

this.editor.post(r)也不能工作,文本渲染之前r仍稱。

+0

爲什麼你沒有使用TextWatcher ??? –

+0

@hamid_c不知道,但我認爲在UI更新之前運行,不是嗎? –

+0

確切地說,'afterTextChanged(...)'會爲你解決問題。 – Wizard

回答

0

我最初想耽誤工作,因爲它是CPU密集型的。我意識到,解決辦法是旋轉了一個新的線程的工作,而不是將其張貼到UI線程。

1

使用此它將HLP

mSongNameTextView.addTextChangedListener(new TextWatcher() { 
      @Override 
      public void beforeTextChanged(CharSequence s, int start, int count, int after) { 

      } 

      @Override 
      public void onTextChanged(CharSequence s, int start, int before, int count) { 

      } 

      @Override 
      public void afterTextChanged(Editable s) { 

      } 
     }); 
1

您可以將TextWatcherEditText

A TextWatcher基本上是一個偵聽器,用於偵聽EditText中文本(之前,期間和之後)的更改。

它可以實現如下:

EditText et; 
et.addTextChangedListener(new TextWatcher() { 
    public void afterTextChanged(Editable s) { 
     // Work that needs to be done right after the text is displayed 
    } 
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {} 
    public void onTextChanged(CharSequence s, int start, int before, int count) {} 
} 

所以,當你明確地設置文本,這個監聽器應該叫和文本更改之後,// Work that needs to be done right after the text is displayed代碼會被執行。

+0

EdmDroid,謝謝你的回答。不幸的是,'afterTextChanged'沒有幫助:在繪製任何東西之前,回調仍然被調用。 –

0

您可以如下使用ViewTreeObserver

yourView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
     @Override 
     public void onGlobalLayout() { 
      // do your work here. This call back will be called after view is rendered. 
      yourView.getViewTreeObserver().removeOnGlobalLayoutListener(this); 
      // or below API 16: yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this); 

     } 
    }); 
+0

我剛試過。不幸的是,這似乎也不起作用。 –

+0

它應該工作。也許是因爲你的代碼。你也應該發佈你的代碼。 –