Android攻城狮之Toast
目录
Toast简介
Toast是一种提供给用户简介提示信息的视图。如下图:
该视图以浮于应用程序之上的形式呈现给用户。Toast提示界面不获取焦点,所以不影响用户的操作。Toast提示就是在不影响用户使用程序的同时,给用户提供某些提示信息。有两个例子就是音量控制和设置信息保存成功。
Android 提供的Toast类可以创建和显示该Toast信息。
Toast常用方法
toast.makeText(context, text, duration); //返回值为toast
toast.setDuration(duration); //设置持续时间
toast.setGravity(gravity, xOffset, yOffset); //设置toast位置
toast.setText(s); //设置提示内容
toast.show(); //显示
Toast具体实现
在布局文件中添加Button组件,id=toast_btn
默认的Toast
private void initEvent(){
findViewById(R.id.toast_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showToast1();
}
});
}
private void showToast1(){
Toast toast = Toast.makeText(this,"默认的Toast",Toast.LENGTH_LONG);
toast.show();
}
改变位置的Toast
showToast2()
函数如下
private void showToast2(){
Toast toast = Toast.makeText(this,"改变位置的Toast",Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
涵盖图片的Toast
showToast3()
函数如下
private void showToast3(){
Toast toast = Toast.makeText(this,"涵盖图片的Toast",Toast.LENGTH_LONG);
LinearLayout toast_layout = (LinearLayout)toast.getView();
ImageView iv = new ImageView(R.drawable.toping);
toast_layout.addView(iv,0);
toast.show();
}
自定义的Toast
自定义Toast时,需要创建一个布局文件。布局文件中控件如下
<TextView
android:layout_width="fill_parent"
android:layout_height="30dip"
android:gravity="center"
android:text="这是个自定义的Toast"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="我们可以随便写"/>
其中showToast4()
函数如下
private void showToast4(){
LayoutInflater inflater = LayoutInflater.from(this);
View toast__view = inflater.inflate(R.layout.toast_layout,null);
Toast toast = new Toast(this);
toast.setView(toast__view);
toast.show();
}