Toast是一种没有交点,显示时间有限,不能与用户进行交互,用于显示提示信息的显示机制,我们可以把它叫做提示框。Toast是没有依赖性的,大家可能比较了解Dialog等其他显示方式,他们是必须依赖于Activity的,必须通过在Activity中的调用才可以使用。而Toast则不依赖于Activity,也就是说,没有Activity,依然可以使用Toast。
Android的四大组件:Activity, Service, Broadcast Receiver, Contet Provider,都是继承Context的(Context,现在大家称之为上下文,之前又被翻译为句柄。),包括整个Application也是继承于Context的。Toast就是依赖于应用程序Application的Context。
Toast有个静态方法makeText,一般情况下使用Android中的Toast都是通过这个方法来获得Toast对象的。
我们首先来看一下makeText方法:
Context context:是指Toast依赖的Application的Context,这里我们通过方法getApplicationContext()来获得。
CharSequence text:是指Toast中显示的内容。
int duration:是指Toast显示的时间,这里通过Toast中的两个常量LENGTH_SHORT和LENGTH_LONG来定义。
Toast toast = Toast.makeText(getApplication(), 这是一个Toast,Toast.LENGTH_SHORT);
//通过show()方法来调用Toast
toast.show();
这里我们通过一个安检的监听事件来触发Toast,具体代码不再贴出,看结果:
Toast的显示位置是可以修改的,通过如下语句:
toast.setGravity(Gravity.CENTER | Gravity.LEFT, 0, 0);
也可以设置富文本:
Spanned spanned = Html.fromHtml(This is a Error! , new Html.ImageGetter() {
@Override
public Drawable getDrawable(String s) {
Drawable drawable = getResources().getDrawable(R.mipmap.ic_launcher);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
return drawable;
}
}, null);
toast1.setText(spanned);
有可能大家会觉得Android自带的Toast界面不好看,那么我们可以自定义一个。
1. 定义一个Toast布局.
2.通过构造器创建Toast对象
Toast toast2 = new Toast(getApplicationContext());
3. 通过LayoutInflater获取布局
LayoutInflater inflater = getLayoutInflater();
View toastView =inflater.inflate(R.layout.my_toast_layout,null);
4. 通过setView方法将布局设置在Toast中
toast2.setView(toastView);
5. 通过setDurationff 设置显示时长
toast2.setDuration(Toast.LENGTH_SHORT);
6. 通过show方法调用
toast2.show();
MainA的代码:
public class MainActivity extends Activity implements OnClickListener {
private Button mButtonToast;
private Button mButton2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButtonToast = (Button) findViewById(R.id.button_toast);
mButton2 = (Button) findViewById(R.id.button2);
mButtonToast.setOnClickListener(this);
mButton2.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button_toast:
Toast toast1 = Toast.makeText(getApplicationContext(), 这是一个Toast,Toast.LENGTH_LONG);
Spanned spanned = Html.fromHtml(This is a Error! , new Html.ImageGetter() {
@Override
public Drawable getDrawable(String s) {
Drawable drawable = getResources().getDrawable(R.mipmap.ic_launcher);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
return drawable;
}
}, null);
toast1.setText(spanned);
toast1.setGravity(Gravity.CENTER | Gravity.LEFT, 0, 0);
toast1.show();
break;
case R.id.button2:
Toast toast2 = new Toast(getApplicationContext());
LayoutInflater inflater = getLayoutInflater();
View toastView =inflater.inflate(R.layout.my_toast_layout,null);
toast2.setView(toastView);
toast2.setDuration(Toast.LENGTH_SHORT);
toast2.show();
break;
default:
break;
}
}
}