首页 > 移动平台 > 详细

Android笔记--自定义控件 Toast

时间:2014-01-17 09:04:19      阅读:476      评论:0      收藏:0      [点我收藏+]

在做一个Android项目时,Toast用到的地方非常多.但是原生控件确实不好看.所以自己定义一个好看的.

这里主要记录一个方法:showShortToast

bubuko.com,布布扣
 /**
     * 短暂显示Toast消息
     *
     * @param context
     * @param message
     */
public static void showShortToast(Context context, String message) {

        //对于已经载入的Activity,那么用findById来查找.但是没有载入或者想要动态载入的Activity.我们采用LayoutInflater
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //通过布局文件.查找自定义的toast
        View view = inflater.inflate(R.layout.custom_toast, null);
        //找到后再findById
        TextView text = (TextView) view.findViewById(R.id.toast_message);
        //设置toast的显示信息
        text.setText(message);
        //实例化toast
        Toast toast = new Toast(context);
        //设置显示时间长短
        toast.setDuration(Toast.LENGTH_SHORT);
        //显示位置
        toast.setGravity(Gravity.BOTTOM, 0, 300);
        //设置view
        toast.setView(view);
        //show
        toast.show();
    }
bubuko.com,布布扣

其中首先获得inflater:  在Activity里面就使用了LayoutInflater来载入界面, 通过getSystemService(Context.LAYOUT_INFLATER_SERVICE)方法可以获得一个 LayoutInflater, 也可以通过LayoutInflater inflater = getLayoutInflater();来获得.然后使用inflate方法来载入layout的xml.

得到inflater后,就可以得到View对象.通过view对象的findById()获得id="toast_message"的控件.设置标题等.

 

其中custom_toast.xml如下:

 

bubuko.com,布布扣
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/toast_bg"
    android:padding="10dp" >

    <ImageView
        android:id="@+id/toast_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:background="@drawable/toast_icon" />

    <TextView
        android:id="@+id/toast_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@id/toast_icon"
        android:gravity="center"
        android:maxLines="2"
        android:textColor="@color/toast_color"
        android:textSize="12sp" />

</RelativeLayout>
bubuko.com,布布扣

xml中的图片可以根据自己爱好设置.

Android笔记--自定义控件 Toast

原文:http://www.cnblogs.com/onivyway/p/3523097.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!