android中自定义Toast方法详解(一)

本文详细解析了如何在Android开发中自定义Toast,包括深入分析makeText()方法,探讨布局文件与TN类的作用,以及如何通过WindowManager显示和移除自定义Toast。通过设置点击事件和Handler,实现了自定义Toast的定时消失功能。
摘要由CSDN通过智能技术生成

在进行android开发时,我们经常用到Toast来给用于进行提示,大部分情况下android中提供给我们的默认方法基本上能够解决问题。但问题是有些用户嫌android原生的Toast不好看,想定义属于他们自己风格的Toast。考虑到别具一格的Toast确实能给用于耳目一新的感觉,因此我们也有了仔细去分析它实现细节的理由哈。先来看看demo中显示的android原生的Toast风格。

public void startToast(View view){
        Toast.makeText(MainActivity.this, "您点击了Button按钮", 
        Toast.LENGTH_SHORT).show();
}


为了一探究竟,我们进入makeText()方法中,我们来看看android中是怎样来实现该方法的:

//android官方的makeText方法
public static Toast makeText(Context context, CharSequence text, @Duration 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;
}

从代码中可以看出,其实就是用LayoutInflater系统方法导入了一个android中内置的布局文件,我们再来看看这个原生的布局文件:

//com.android.internal.R.layout.transient_notification布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="?android:attr/toastFrameBackground">

    <TextView
        android:id="@android:id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="center_horizontal"
        android:textAppearance="@style/TextAppearance.Toast"
        android:textColor="@color/bright_foreground_dark"
        android:shadowColor="#BB000000"
        android:shadowRadius="2.75"
        />

</LinearLayout>

com.android.internal.R.id.message就是这上面的TextView控件的ID。makeText方法中传入的text的参数赋值给了TextView。接着又把View赋值给了Toast的成员函数并返回了一个Toast类型的对象。说白了这里其实就是通过makeText方法构造出了一个Toast类型的对象,然后将android中内置的布局文件转成一个View对象以及显示的时间传给Toast的成员变量。

再来看看show()方法的实现原理。

//show()方法
public void show() {
        if (mNextView == null) {
            throw new RuntimeException("setView must have been called");
        }

        INotificationManager service = getService();
        String pkg = mContext.getOpPackageName();
        TN tn = mTN;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值