继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

android 自定义Toast

弑天下
关注TA
已关注
手记 141
粉丝 12
获赞 51

Toast是android的一个简易消息提示框。

         它不会获得焦点,也无法被点击。向用户提示信息,却不停留着不动。

        其实,自定义Toast非常简单:

         先看效果:

                5be45b1100015b1703020135.jpg

          首先:新建一个mtoast.xml布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@null"
    android:gravity="center_vertical"
    android:orientation="horizontal" >
    <RelativeLayout
        android:id="@+id/RelativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="34dp" >
        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:src="@drawable/display_bg_2" />
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:textColor="@android:color/white"
            android:text="TextView" />
    </RelativeLayout>
</LinearLayout>

在定义一个mTools.java文件:

    public class mTools extends Toast{
    private static Toast resToast;
public mTools(Context context) {
super(context);
}
public static void  showToast(Context context,int resId,CharSequence text,int duration){
//获取系统的LayoutInflater
LayoutInflater inflater =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//加载布局文件
View view=inflater.inflate(R.layout.mtoast, null);
//实例化控件
ImageView imageView=(ImageView) view.findViewById(R.id.imageView1);
TextView textView=(TextView) view.findViewById(R.id.textView1);
//设置控件要显示的东西
imageView.setImageResource(resId);
textView.setText(text);
//实例化Toast
resToast=new Toast(context);
resToast.setView(view);     //设置要显示的view
resToast.setGravity(Gravity.CENTER, 0,0); //设置在屏幕的什么位置显示
resToast.setDuration(duration); //显示的时间长短
resToast.show();  //show
}
}

那么你只需要在Activity中

           mTools.showToast(MainActivity.this,R.drawable.display_bg_2,"测试Toast", Toast.LENGTH_SHORT);

就OK了,一个自定义的Toast就出来了!!!!!!!!

原文链接:http://www.apkbus.com/blog-524160-59269.html

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP