我正在创建一个程序,当用户单击该按钮时,onclick中会调用asynctask。但每次用户点击按钮时文本都会发生变化......我怎么能实现一些我可以调用的东西来利用异步方法。
这是我的意思的一个例子
public void Talk(){
text1.setText("Welcome what is your name?");
respond.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
name = edit.getText().toString();
new AsyncTask<Void, Integer, Void>(){
@Override
protected Void doInBackground(Void... arg0) {
try {
Thread.sleep(850);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
text1.setText("Nice to meet you "+name);
dismissDialog(typeBar);
}
@Override
protected void onPreExecute() {
typeBar = 0;
showDialog(typeBar);
}
}.execute((Void)null);
}
});
}
因此,当您看到evertime时,用户按下按钮,文本会发生变化。单击按钮,输入ayncTask方法非常繁琐。有人知道我能做到这一点吗?
答案 0 :(得分:1)
我会忽略你为什么要使用AsyncTask进行任何操作。不要使用内联类。在您的活动中创建一个私人类:
private class MyAsyncTask extends AsyncTask<String, Void, Void>
并重复使用它,例如:
MyAsyncTask.execute("Whatever")