2017-06-20 47 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

它应该工作。也许是因为你的代码。你也应该发布你的代码。 –