如何在 Android 中显示 Toast? [英] How to display Toast in Android?
问题描述
我有一个可以拉起的滑块,然后它会显示一张地图.我可以上下移动滑块来隐藏或显示地图.当地图在前面时,我可以处理该地图上的触摸事件.每次我触摸时,都会启动一个 AsyncTask
,它会下载一些数据并制作一个显示数据的 Toast
.虽然我在触摸事件上开始任务,但没有显示吐司,直到我关闭滑块.当滑块关闭且地图不再显示时,Toast
出现.
I have a slider that can be pulled up and then it shows a map. I can move the slider up and down to hide or show the map. When the map is on front, I can handle touch events on that map. Everytime I touch, a AsyncTask
is fired up, it downloads some data and makes a Toast
that displays the data. Although I start the task on touch event no toast is displayed, not till I close the slider. When the slider is closed and the map is not displayed anymore the Toast
appears.
有什么想法吗?
好的开始任务
public boolean onTouchEvent(MotionEvent event, MapView mapView){
if (event.getAction() == 1) {
new TestTask(this).execute();
return true;
}else{
return false;
}
}
并在 onPostExecute
中干杯
Toast.makeText(app.getBaseContext(),(String)data.result,
Toast.LENGTH_SHORT).show();
在新的 TestTask(this)
中,这是对 MapOverlay
的引用,而不是对 MapActivity
的引用,所以这就是问题所在.>
In new TestTask(this)
, this is a reference to MapOverlay
and not to MapActivity
, so this was the problem.
推荐答案
为了显示 Toast,试试这个:
In order to display Toast in your application, try this:
Toast.makeText(getActivity(), (String)data.result,
Toast.LENGTH_LONG).show();
另一个例子:
Toast.makeText(getActivity(), "This is my Toast message!",
Toast.LENGTH_LONG).show();
我们可以为持续时间定义两个常量:
We can define two constants for duration:
int LENGTH_LONG 长时间显示视图或文本通知时间.
int LENGTH_LONG Show the view or text notification for a long period of time.
int LENGTH_SHORT 在短时间内显示视图或文本通知时间.
int LENGTH_SHORT Show the view or text notification for a short period of time.
自定义您的吐司
LayoutInflater myInflater = LayoutInflater.from(this);
View view = myInflater.inflate(R.layout.your_custom_layout, null);
Toast mytoast = new Toast(this);
mytoast.setView(view);
mytoast.setDuration(Toast.LENGTH_LONG);
mytoast.show();
这篇关于如何在 Android 中显示 Toast?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!