Android AsyncTask 实例或类
我正在制作一个程序,当用户单击按钮时,将在 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);
}
});
}
所以正如您所看到的,每次用户按下按钮时文本都会发生变化。每次单击按钮时都键入 ayncTask 方法肯定会很乏味。有人知道我可以这样做吗?
I am making a program that when the user clicks the button the asynctask is called in onclick. But everytime the user clicks the button the text changes... How can i implement something that i can call just to utilize the async method.
Here is a example of what i mean
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);
}
});
}
So as you can see evertime the user presses the button the text changes. It will definitely be to tedious to type the ayncTask method EVERYTIME the button is clicked. Anyone know a way i could do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会忽略你为什么要使用 AsyncTask 来完成你正在做的任何事情。不要使用内联类。在您的活动中创建一个私有类:
并重用它,例如:
I'll just ignore why you're using an AsyncTask for whatever you're doing. Don't use an inline class. Create a private class within your Activity:
And reuse it, e.g.: