最新消息:关注【太平洋学习网】微信公众号,可以获取全套资料,【全套Java基础27天】【JavaEE就业视频4个月】【Android就业视频4个月】

自定义Toast弹出窗口|Android教程

Android 太平洋学习网 浏览 评论

如果我们在android中对系统默认的Toast不满意,我们也可以自定义Toast弹出消息窗口,使用很简单,就是new --- file --- xml --- layout xml file自定义一个layout布局文件,然后使用Toast对象的setView方法将自定义的layout布局设置进去即可,请看步骤:

1创建custom_toast_layout.xml文件,创建步骤:new --- file --- xml --- layout xml file,代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp"
    android:background="#111">

    <TextView android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FFF"/>

    <TextView android:id="@+id/description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FFF"/>
</LinearLayout>

2:添加一个Button按钮,给它一个点击事件,用于测试toast弹出,代码就不展示了。

3:在MainActivity.java文件实现button的点击事件,如showToast()方法,代码如下:

    public void showToast(View view){

        LayoutInflater inflater = getLayoutInflater();
        
        //通过inflater对象加载自定义文件
        View layout = inflater.inflate(R.layout.custom_toast_layout,
                (ViewGroup) findViewById(R.id.toast_layout_root));

        // Set the title and description TextView from our custom layout
        //设置TextView标题与描述
        TextView title = (TextView) layout.findViewById(R.id.title);
        title.setText("Toast Title");

        TextView description = (TextView) layout.findViewById(R.id.description);
        description.setText("Toast Description");

        // Create and show the Toast object
        //创建Toast对象并展示toast
        Toast toast = new Toast(getApplicationContext());
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.show();
    }

点击效果如图:

toast.jpg

完毕!

来源网站:太平洋学习网,转载请注明出处:http://www.tpyyes.com/a/android/532.html
"文章很值,打赏犒劳作者一下"
微信号: Javaweb_engineer

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

与本文相关的文章

发表我的评论
取消评论

表情

您的回复是我们的动力!

  • 昵称 (必填)

网友最新评论