0
经过多年拖网试图找到一个可以理解的解决方案,我放弃了我的问题,并来到这里看看你是否可以提供帮助。在ASyncTask中更新TextView
我的目标:更新一个TextView从1到99999每秒计数而不挂主线程。
package com.myapp.counter;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBackgroundThread myThread = new myBackgroundThread();
myThread.execute();
}
private class myBackgroundThread extends AsyncTask<Void,Integer,Void>
{
int maxTimer = 99999;
int i = 0;
//Assign the textView in MainActivity to a variable myCounter.
TextView myCounter = (TextView)findViewById(R.id.idCounter);
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... params) {
// Toast.makeText(getApplicationContext(),"InBackground",Toast.LENGTH_SHORT).show();
//Tried Toasting a message upon this starting but just threw an error
//Guess because i tried to add a UI component in a background task.
for(int i = 0; i < maxTimer; i++)
{
publishProgress(i);
}
return null;
}
//onProgressUpdate is never firing from publishProgress...
protected void onProgressUpdate(Integer i) {
Toast.makeText(getApplicationContext(),i,Toast.LENGTH_SHORT).show();
//Updatet he counter from 000 to 1,2,3,4 etc.
myCounter.setText(i);
}
protected void onPostExecute(Void result)
{
}
}
public void startTimer(View view)
{
TextView myText = (TextView)findViewById(R.id.textView);
// Toast.makeText(this,"Started...", Toast.LENGTH_SHORT).show();
}
public void stopTimer(View view) {
Toast.makeText(this, "Stopped...", Toast.LENGTH_SHORT).show();
}
}
我似乎无法看到为什么publishProgress不会火,我想从按下按钮执行的AsyncTask。
我有3个元素2个按钮startTimer和stopTimer和1个textview在后台更新。
非常感谢所有。
不onProgressUpdate总是要求值的数组传递给它?正如我见过的每个例子似乎总是通过获取其索引来检索值...即值... [0] – Shabalaka
根据官方文档,是的。 – Abhinash