Android之Notification实现


在我们的相应程序运行的时候为了不打断当前程序的运行,我们经常会使用Notification来告知用户有新来电或新的短信。

下面先介绍一下toast的简单提醒:

  1. private void baseToast(){  
  2.     Toast.makeText(getApplicationContext(), "Hello toast!", Toast.LENGTH_SHORT).show();  
  3.   }  

 第一个参数是得到上下文,第二个是提醒的具体内容,第三个是提醒的时间。


接下来看一下如何自定义一个Toast提醒:

  1. //自定义toast  
  2.    private void customToast(){  
  3.     //得到inflater对象和view  
  4.     LayoutInflater inflater=getLayoutInflater();  
  5.     View layout=inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));  
  6.     //得到view下的相应的控件  
  7.     ImageView image = (ImageView) layout.findViewById(R.id.image);  
  8.     image.setImageResource(R.drawable.ic_launcher);  
  9.     TextView text = (TextView) layout.findViewById(R.id.text);  
  10.     text.setText("Hello! This is a custom toast!");  
  11.     //设置toast  
  12.     Toast toast=new Toast(getApplicationContext());  
  13.     toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);  
  14.     toast.setDuration(Toast.LENGTH_SHORT);  
  15.     toast.setView(layout);  
  16.     toast.show();  
  17.   
  18.    }  

在layout 下定义了toast_layout.xml布局文件:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"  
  3.               android:id="@+id/toast_layout_root"  
  4.               android:orientation="horizontal"  
  5.               android:layout_width="fill_parent"  
  6.               android:layout_height="fill_parent"  
  7.               android:padding="10dp"  
  8.               android:background="#DAAA"  
  9.               >  
  10.     <ImageView android:id="@+id/image"  
  11.                android:layout_width="wrap_content"  
  12.                android:layout_height="fill_parent"  
  13.                android:layout_marginRight="10dp"  
  14.                />  
  15.     <TextView android:id="@+id/text"  
  16.               android:layout_width="wrap_content"  
  17.               android:layout_height="fill_parent"  
  18.               android:textColor="#FFF"  
  19.               />  
  20. </LinearLayout>  

运行后效果:

  • 1
  • 2
  • 下一页

相关内容