android自定义toast(widget开发)示例
1、Toast控件:
通过查看源代码,发现Toast里面实现的原理是通过服务Context.LAYOUT_INFLATER_SERVICE获取一个LayoutInflater布局管理器,从而获取一个View对象(TextView),设置内容将其显示
public static Toast makeText(Context context, CharSequence text, int duration) {
Toast result = new Toast(context);
LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
tv.setText(text);
result.mNextView = v;
result.mDuration = duration;
return result;
}
定义布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="@+id/iv_my_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/notification" />
<TextView
android:id="@+id/tv_my_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="text"
/>
</LinearLayout>
自定义MyToast类:
public class MyToast {
/**
* 显示自定义的土司
* @param context 上下文
* @param iconid 图标的id
* @param text 显示的文本
*/
public static void showToast(Context context,int iconid, String text){
View view = View.inflate(context, R.layout.my_toast, null);
TextView tv = (TextView) view.findViewById(R.id.tv_my_toast);
ImageView iv = (ImageView) view.findViewById(R.id.iv_my_toast);
iv.setImageResource(iconid);
tv.setText(text);
Toast toast = new Toast(context);
toast.setDuration(0);
toast.setView(view);
toast.show();
}
}
相关文章
Android实现EditText控件禁止输入内容的方法(附测试demo)
这篇文章主要介绍了Android实现EditText控件禁止输入内容的方法,涉及Android针对EditText控件属性设置的相关技巧,需要的朋友可以参考下2015-12-12ubuntu 12.10 上 android 编译环境搭建的深入解析
本篇文章是对ubuntu 12.10上android 编译环境的搭建进行了详细的分析介绍,需要的朋友参考下2013-06-06Android RecyclerView网格布局(支持多种分割线)详解(2)
这篇文章主要为大家详细介绍了Android RecyclerView网格布局,支持多种分割线,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-02-02Android Cocos Creator游戏开发平台打包优化实现方案
Cocos Creator是一款轻量、高效、免费开源的跨平台游戏引擎,同时也是实时3D内容创作平台,不仅支持2D、3D的游戏开发,同时在HMI、IoT、XR、虚拟人偶等领域,均可提供一套完善的行业解决方案2022-11-11
最新评论