runOnUiThread settext 仅在循环中的第一次工作

runOnUiThread settext only works at the first time during a loop

我有一个由 expandListAdpater 填充的 Textview 数组列表,我的目标是更改 textView 的值,但由于某种原因它只能工作一次。我尝试了不同的计时器,试图将我的处理程序绑定到 ui 线程,但它从来没有用过。这是我的代码。请帮忙! 展开列表适配器…

TextView mytexts= ButterKnife.findById(view, R.id.mytexts);
mySubSections.add(new ConstructForKeepingTextviewsForUpdate(mytexts));
// I got about 10 more textviews , this is an example

public class ConstructForKeepingTextviewsForUpdate {
    private TextView getTextviewToBeUpdated() {
        return textviewToBeUpdated;
    }

    public void SetVal(String t){
        getTextviewToBeUpdated().setText(t);
    }


    TextView textviewToBeUpdated;

    public ConstructForKeepingTextviewsForUpdate(TextView textviewToBeUpdated) {
        this.textviewToBeUpdated = textviewToBeUpdated;
        }

}

in onCreate I run this

private void pleaseWork(){
    new Timer().schedule(new TimerTask() {

        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                public void run() {
                    updateNumbersInLoop();
                }
            });
        }
    }, 0, 1000);
}

public static void updateNumbersInLoop() {
    for (ConstructForKeepingTextviewsForUpdate subSec : mySubSections){
       String datext = dbHelper.getValue (computedValue);
       subSec.SetVal(datext); 
    }
}
//The getValue function works , I can see the correct value, but the settext works only once, at the first time.

我经常遇到类似的问题。我尝试了所有不同的方法。现在我正在使用 AsynTasc 来避免这种情况。它有一个名为 onProgressUpdate() 的方法。它在 UI 线程上运行,在此方法中您可以更新您的 TextView。计算本身(例如你的循环)可以在 doInBackground() 方法中处理。这个方法是运行在自己的Thread中。总是当你想更新你的 TextView 时,你将在 doInBackground() 方法中调用 publishProgress("YourText") 。然后该参数将传递给 onProgressUpdate(),您的 TextView 将在其中更新。

    private class MultiplayerIntro extends AsyncTask<Void, String, Void> {

    @Override
    protected Void doInBackground(Void... result) {
        try{
        String text;
        for(...){
            text = ...;
            publishProgress(text);
            Thread.sleep(2000);
        }
    } catch (InterruptedException e) {
        // ...
    ]
        return null;
    }

    @Override
    protected void onProgressUpdate(String... progress) {
         yourTextView.setText(progress[0]);
    }

    @Override
    protected void onPostExecute(Void result) {
         // ...
    }
}

然后你开始任务:

new MultiplayerIntro().execute();

你可以在这里找到许多参数的很好的解释: Whosebug

实际上,当我玩代码时,asyncTask 给出了相同的结果。显然,出于某种原因,您不能将 textview 作为对象传递。所以真正有效的是

TextView myTextV=  (TextView) findViewById(ConstructForKeepingTextviewsForUpdate.getItsID());
myTextV.setText("anything you like");

您应该做的是将 id 作为整数传递。