代码之家  ›  专栏  ›  技术社区  ›  seba123neo

从函数android更新textview

  •  3
  • seba123neo  · 技术社区  · 15 年前

    有人能告诉我如何从函数更新控件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");
    
    };
    

    事先谢谢。

    3 回复  |  直到 15 年前
        1
  •  5
  •   Labeeb Panampullan    15 年前


    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]);
         }
    
    
     }
    
        2
  •  3
  •   rwat    15 年前

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

        3
  •  1
  •   dlongest    15 年前

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

    myTextView.setText("New text example");