簡體   English   中英

從Android功能更新Textview

[英]Update Textview from function Android

有人可以告訴我如何從一個函數更新控件Textview Android? 我已深入搜索互聯網並看到許多人提出同樣的問題,我測試了線程但無法工作,有人有一個簡單的工作示例嗎? 例如,調用一個函數(在循環中運行幾次)並且函數在TextView中寫入,但問題是在函數未完成運行之前,它會向我顯示文本。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    while(condition) //here freezes the UI and the text in textview only shows when the loop ends
    {
        HardWork();  
    }

}

public void HardWork() {  

    txtProgreso.append("Test Line" + "\n\n");

};

提前致謝。

如果我理解正確的話
在這里使用AsyncTask,因此您可以在onProgressUpdate方法中更新textview

private class SomeTask extends AsyncTask<String, String, String> {
    @Override
        protected String doInBackground(String... params) {
         while(condition) {
         //do more
         publishProgress("Some text value to you textview");
        }
         return null;
     }

     @Override
     protected void onProgressUpdate(String... values) {
         txtProgreso.append(values[0]);
     }


 }

我想你要問的是“我如何強制我的TextView顯示其更新的內容而不將控制返回到runloop?” (即退出你的職能)。

如果是這樣,我擔心你運氣不好,這樣的事情與Android的UI模型無關。 最接近這一點的是跟蹤你的循環狀態,並設置一個定時器,它將調用一個函數來更新TextView。

這是一個例子。 假設您要將文本“this is a test”放入TextView,一次一個字符:

private Handler mHandler = new Handler();
private String desiredText = new String("This is a test");

private Runnable mUpdateTextView = new Runnable() {
  public void run() {
    TextView textView = (TextView)findViewById(R.id.myTextView);
    int lengthSoFar = textView.getText().length();
    if (lengthSoFar < desiredText.length()) {
      mTextView.setText(desiredText.substring(0, lengthSoFar + 1));
      mHandler.postDelayed(100, mUpdateTextView);
    }
  }
};

protected void onStart() {
  mHandler.postDelayed(100, mUpdateTextView);
}

我認為我的一些對象可見性在這里是不正確的,並且我沒有便於測試的Android環境,但是你得到了一般的想法。 而不是處理程序,你也可以使用計時器,但它更重要,所以它取決於你想要更新UI的頻率。

您可以通過執行以下操作獲取textview。

TextView myTextView = (TextView)findViewById(R.id.textViewsId);

然后,您可以使用這些功能更改TextView。 例如,您可以使用以下代碼設置文本。

myTextView.setText("New text example");

您正在嘗試執行的控件是否還有其他更新?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM