我想要显示Toast消息"正在处理..请等待。"在用户按下listview项目后进行一些处理。从lv.setOnItemClickListener调用时,AsyncTask不起作用(但是从button.setOnClickListener调用时有效)。
知道为什么吗?
MyActivity.java
public class MyActivity extends Activity {
private static Context context;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
context = this;
ListView lv = (ListView) findViewById(R.id.listView);
Button button = (Button) findViewById(R.id.btn);
// this DOESN't show the waiting message while processing
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
new AsyncMsg(position).execute();
}
});
// this shows the waiting message while processing
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int position = 0; //first item
new AsyncMsg(position).execute();
}
});
}
public static void showWaitMessage() {
Toast.makeText(context, "Processing.. Please wait.", Toast.LENGTH_SHORT)
.show();
}
}
AsyncTask:AsyncMsg.java
public class AsyncMsg extends AsyncTask<Void, Void, Void> {
public int position;
public AsyncMsg(int position) {
this.position = position;
}
public void onPreExecute() {
MyActivity.showWaitMessage();
}
@Override
protected Void doInBackground(Void... params) {
// do some long process with position
}
public void onPostExecute() {
}
}
答案 0 :(得分:1)
为什么不尝试这个
public class AsyncMsg extends AsyncTask<Void, Void, Void> {
public int position;
Context context;
public AsyncMsg(int position,Context con) {
this.position = position;
context =con;
}
public void onPreExecute() {
Toast.makeText(context, "Processing.. Please wait.", Toast.LENGTH_SHORT)
.show();
}
}
然后像这样打电话
new AsyncMsg(position,context).execute();
答案 1 :(得分:0)
在Toast.make(..)中用作上下文MyActivity.this
。