Toast.makeText是Android中用于显示短暂的消息提示的工具类,常见的用法有以下几种
Toast.makeText是Android中用于显示短暂的消息提示的工具类,常见的用法有以下几种:
-
显示简单的文本消息:
Toast.makeText(context,"HelloWorld!",Toast.LENGTH_SHORT).show();
-
设置消息的显示时长:
Toast.makeText(context,"HelloWorld!",Toast.LENGTH_LONG).show();
-
自定义消息的位置:
Toasttoast=Toast.makeText(context,"HelloWorld!",Toast.LENGTH_SHORT); toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL,0,0); toast.show();
-
使用自定义的布局显示消息:
LayoutInflaterinflater=getLayoutInflater(); Viewlayout=inflater.inflate(R.layout.custom_toast,findViewById(R.id.custom_toast_container)); TextViewtext=layout.findViewById(R.id.text); text.setText("HelloWorld!"); Toasttoast=newToast(getApplicationContext()); toast.setDuration(Toast.LENGTH_SHORT); toast.setView(layout); toast.show();
-
在后台线程中使用Toast消息:
runOnUiThread(newRunnable(){ @Override publicvoidrun(){ Toast.makeText(context,"HelloWorld!",Toast.LENGTH_SHORT).show(); } });
这些是Toast.makeText的几个常见用法,开发者可以根据自己的需求选择适合的用法来显示消息提示。
版权声明
本文仅代表作者观点,不代表博信信息网立场。