您的位置:首页 > 其它

Toast的各类用法大全(有Demo)

2014-09-11 17:52 253 查看
在安卓用户交互开发中Toast深受广大开发者喜爱,大多通过makeText方法返回对象显示,却没有深入研究这个对象,其实他还有很多强大功能

1.正常显示

//注意: 使用的时候新手容易将.show()漏掉, 不使用该方法Toast是不会显示的

Toast.makeText(getApplicationContext(), btnName[0], Toast.LENGTH_SHORT).show();


2.自定位置显示

//使用.setGravity()这个方法可以设置Toast的位置和偏移量

Toast toast = Toast.makeText(getApplicationContext(), btnName[1], Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();


3.带图片显示

//获取toas的tView,利用addView()添加图片显示

Toast toast = Toast.makeText(getApplicationContext(), btnName[2], Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 50, 0);
LinearLayout layout = (LinearLayout) toast.getView();
ImageView image = new ImageView(getApplicationContext());
image.setImageResource(R.drawable.ic_launcher);
layout.addView(image, 0);
toast.show();


4.自定View显示

LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.view_toast, null, false);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(view);
toast.show();


5.长时间显示

{
//直接自定义AlertDialog显示即可

LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.view_toast, null, false);
builder = new AlertDialog.Builder(this);
builder.setView(view);
dialog = builder.create();
dialog.show();
}


其实这个已经不属于Toast这个对象了,但是我们却可以通过他实现我们想要的

6. 定时显示

AlertDialog.Builder builder;
AlertDialog dialog;

/**** 长时间显示  ****/
protected void startToast5()
{
//直接自定义AlertDialog显示即可

LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.view_toast, null, false);
builder = new AlertDialog.Builder(this);
builder.setView(view);
dialog = builder.create();
dialog.show();
}

//定时显示
protected void startToast6()
{
//通过Timer指定时间销毁弹出窗口即可实现

long time = 1000; // 此时间以毫秒记

startToast5();
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
@Override
public void run()
{
//到指定时间Kill掉AlertDialog即可
dialog.dismiss();
}
}, time);

}


我就不上图了,不明白的童鞋去下载Demo吧, 地址: download.csdn.net/detail/u010058586/7898195
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: